<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Hdelossantos.com</title>
	
	<link>http://www.hdelossantos.com</link>
	<description>Tales of the Wisconsin Experience</description>
	<lastBuildDate>Fri, 21 May 2010 00:41:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/hdelossantos" /><feedburner:info uri="hdelossantos" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Verilog SyntaxHighlighter Brush</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/XL9VjiSgSMU/</link>
		<comments>http://www.hdelossantos.com/2010/05/20/verilog-syntaxhighlighter-brush/#comments</comments>
		<pubDate>Fri, 21 May 2010 00:40:27 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[highlighter]]></category>
		<category><![CDATA[plug-in]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[syntaxhighlighter]]></category>
		<category><![CDATA[Verilog]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=570</guid>
		<description><![CDATA[I was trying to add some sample Verilog code on my website, but the code syntax highlighter I use did not have a brush. I made my own Verilog brush for Alex Gorbatchev&#8217;s SyntaxHighlighter. Feel free to modify and improve the code. The only thing that I ask is that you share the modifications.

/**
 * [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to add some sample Verilog code on my website, but the code syntax highlighter I use did not have a brush. I made my own Verilog brush for Alex Gorbatchev&#8217;s<a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter"> SyntaxHighlighter</a>. Feel free to modify and improve the code. The only thing that I ask is that you share the modifications.</p>
<pre class="brush: jscript;">
/**
 * SyntaxHighlighter Verilog Brush
 * http://hdelossantos.com/
 *
 * SyntaxHighlighter is donationware. If you are using it, please donate.
 * http://alexgorbatchev.com/wiki/SyntaxHighlighter:Donate
 *
 * @version
 * 1.0.0 (May 20, 2010)
 *
 * @copyright
 * Copyright (C) 2010 Hanly De Los Santos.
 *
 * @license
 * This file is a SyntaxHighlighter brush and is licensed under
 * the same license as SyntaxHighlighter.
 *
 * SyntaxHighlighter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SyntaxHighlighter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SyntaxHighlighter.  If not, see &lt;http://www.gnu.org/copyleft/lesser.html&gt;.
 */
SyntaxHighlighter.brushes.Verilog = function() {
	var keywords = 'always end ifnone or rpmos tranif1 and endcase ' +
			  'initial output rtran tri assign endmodule inout ' +
			  'parameter rtranif0 tri0 begin endfunction input ' +
			  'pmos rtranif1 tri1 buf endprimitive integer ' +
			  'posedge scalared triand bufif0 endspecify join ' +
			  'primitive small trior bufif1 endtable large pull0 ' +
			  'specify trireg case endtask macromodule pull1 ' +
			  'specparam vectored casex event medium pullup ' +
			  'strong0 wait casez for module pulldown strong1 ' +
			  'wand cmos force nand rcmos supply0 weak0 deassign ' +
			  'forever negedge real supply1 weak1 default for ' +
			  'nmos realtime table while defparam function nor ' +
			  'reg task wire disable highz0 not release time wor ' +
			  'edge highz1 notif0 repeat tran xnor else if ' +
			  'notif1 rnmos tranif0 xor';
	var sysTasks = '$display $monitor $dumpall $dumpfile $dumpflush ' +
			  '$dumplimit $dumpoff $dumpon $dumpvars $fclose ' +
			  '$fdisplay $fopen $finish $fmonitor $fstrobe ' +
			  '$fwrite $fgetc $ungetc $fgets $fscanf $fread ' +
			  '$ftell $fseek $frewind $ferror $fflush $feof ' +
			  '$random $readmemb $readmemh $readmemx $signed ' +
			  '$stime $stop $strobe $time $unsigned $write';
	var macros = 'default-net define celldefine default_nettype ' +
			  'else elsif endcelldefine endif ifdef ifndef ' +
			  'include line nounconnected_drive resetall ' +
			  'timescale unconnected_drive undef';

	this.regexList = [
		{ regex: SyntaxHighlighter.regexLib.singleLineCComments,	css: 'comments' },
		{ regex: /\/\*([^\*][\s\S]*)?\*\//gm,						css: 'comments' },
		{ regex: /\/\*(?!\*\/)\*[\s\S]*?\*\//gm,					css: 'preprocessor' },
		{ regex: SyntaxHighlighter.regexLib.doubleQuotedString,		css: 'string' },
		{ regex: SyntaxHighlighter.regexLib.singleQuotedString,		css: 'string' },
		{ regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi,			css: 'value' },
		{ regex: /(?!\@interface\b)\@[\$\w]+\b/g,			css: 'color1' },
		{ regex: /\@interface\b/g,					css: 'color2' },
		{ regex: new RegExp(this.getKeywords(keywords), 'gm'),		css: 'keyword' },
		{ regex: new RegExp(this.getKeywords(macros), 'gm'),		css: 'keyword' },
		{ regex: new RegExp(this.getKeywords(sysTasks), 'gm'),		css: 'keyword' }
];

};

SyntaxHighlighter.brushes.Verilog.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Verilog.aliases = ['verilog', 'v'];
</pre>
<p>You can download the Wordpress plugin below. You must have the SyntaxHighlighter plugin installed and active.</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-2949674902735457";
/* 468x60, created 1/8/10 */
google_ad_slot = "5207313563";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
<a href="/school_content/sample_code/syntaxhighlighter-brush-verilog.zip"><img src="/images/download_now.png" alt="" /></a></p>

	Tags: <a href="http://www.hdelossantos.com/tag/highlighter/" title="highlighter" rel="tag">highlighter</a>, <a href="http://www.hdelossantos.com/tag/plug-in/" title="plug-in" rel="tag">plug-in</a>, <a href="http://www.hdelossantos.com/tag/plugin/" title="plugin" rel="tag">plugin</a>, <a href="http://www.hdelossantos.com/tag/syntax/" title="syntax" rel="tag">syntax</a>, <a href="http://www.hdelossantos.com/tag/syntaxhighlighter/" title="syntaxhighlighter" rel="tag">syntaxhighlighter</a>, <a href="http://www.hdelossantos.com/tag/verilog/" title="Verilog" rel="tag">Verilog</a>, <a href="http://www.hdelossantos.com/tag/wordpress/" title="wordpress" rel="tag">wordpress</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li>No related posts.</li>
	</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/cdCuRzk-E381gq1xVhYQP5J0G94/0/da"><img src="http://feedads.g.doubleclick.net/~a/cdCuRzk-E381gq1xVhYQP5J0G94/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/cdCuRzk-E381gq1xVhYQP5J0G94/1/da"><img src="http://feedads.g.doubleclick.net/~a/cdCuRzk-E381gq1xVhYQP5J0G94/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/XL9VjiSgSMU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2010/05/20/verilog-syntaxhighlighter-brush/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2010/05/20/verilog-syntaxhighlighter-brush/</feedburner:origLink></item>
		<item>
		<title>Using a SQLite Database in Android</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/OqdBhCafyjs/</link>
		<comments>http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 04:08:42 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database adapter]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[step-by-step]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[using database adapter]]></category>
		<category><![CDATA[using dbadapter]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=518</guid>
		<description><![CDATA[This tutorial will demonstrate how to use the database adapter created in &#8220;Creating a SQLite Database in Android&#8221; to add and get data to and from the database to populate a ListView.

DatabaseQuery.java :
We must first create a class to handle the formatting for the queries. The database adapter takes ArrayLists of String objetcs to add [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial will demonstrate how to use the database adapter created in <a href="/2009/12/23/creating-a-sqlite-database-in-android">&#8220;Creating a SQLite Database in Android&#8221;</a> to add and get data to and from the database to populate a ListView.<br />
<span id="more-518"></span></p>
<h3><strong>DatabaseQuery.java :</strong></h3>
<p>We must first create a class to handle the formatting for the queries. The database adapter takes ArrayLists of String objetcs to add rows to the database, however you will probably want a method to add one cell at a time, then when the contents of the row are completed, add the entire row to the database. We begin by declaring the variables for the ArrayLists.</p>
<pre class="brush: java;">
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;

/**
 * This class adds multiple entries to the database and pulls them back
 * out.
 */
public class DatabaseQuery {
	// Variables area
	private ArrayList&lt;String&gt; arrayKeys = null;
	private ArrayList&lt;String&gt; arrayValues = null;
	private ArrayList&lt;String&gt; databaseKeys = null;
	private ArrayList&lt;String&gt; databaseKeyOptions = null;
	private DBAdapter database;
</pre>
<p>We then create the constructor which will call the DBAdapter class and create the database.</p>
<pre class="brush: java;">
/**
	 * Initialize the ArrayList
	 * @param context Pass context from calling class.
	 */
	public DatabaseQuery(Context context) {
		// Create an ArrayList of keys and one of the options/parameters
		// for the keys.
		databaseKeys = new ArrayList&lt;String&gt;();
		databaseKeyOptions = new ArrayList&lt;String&gt;();
		databaseKeys.add(&quot;Title&quot;);
		databaseKeyOptions.add(&quot;text not null&quot;);

		// Call the database adapter to create the database
		database = new DBAdapter(context, &quot;testTable&quot;, databaseKeys, databaseKeyOptions);
        database.open();
		arrayKeys = new ArrayList&lt;String&gt;();
		arrayValues = new ArrayList&lt;String&gt;();

	}
</pre>
<p><strong>databaseKeys</strong> is an ArrayList of all of the column names the database will contain.<br />
<strong>databaseKeyOptions</strong> is an ArrayList of the options for the column names. This can be a field type such as &#8220;text&#8221; or &#8220;integer&#8221;.</p>
<p>In this example I have only added one key here. The DBAdapter class also adds a timeStamp column when a new row is inserted. This makes it easy to sort by time later on. The context is passed from the applications main activity, which we will create at the end. After the DBAdapter object has been created, we then use it to open the pipeline to the database. Now we can query the database.</p>
<p>In the constructor we also initialized two arrays &#8220;arrayKeys&#8221; and &#8220;arrayValues&#8221; which will hold all of the data that constitutes one row. This data is appended to the arrays in the appendData method. Once all of the keys and their values have been appended, then the addRow method is called to insert the row to the database.</p>
<pre class="brush: java;">
/**
	 * Append data to an ArrayList to then submit to the database
	 * @param key Key of the value being appended to the Array.
	 * @param value Value to be appended to Array.
	 */
	public void appendData(String key, String value){
		arrayKeys.add(key);
		arrayValues.add(value);
	}

	/**
	 * This method adds the row created by appending data to the database.
	 * The parameters constitute one row of data.
	 */
	public void addRow(){
		database.insertEntry(arrayKeys, arrayValues);
	}
</pre>
<p>To run a query and get data from the database, we can specify parameters to sort all of the data in the database.</p>
<p><strong>keys</strong> is a String[] of the column headers to return in the results<br />
<strong>selection</strong> is a String to search for in the columns. Only columns with matching string are returned.<br />
<strong>selectionArgs</strong> is a String[] with arguments for the selection.<br />
<strong>groupBy</strong> is the String to group results by.<br />
<strong>having</strong> is a filter to declare which row groups to include in the cursor.<br />
<strong>sortBy</strong> is a key to sort the results by.<br />
<strong>sortOption</strong> specifies the way to sort the data.</p>
<pre class="brush: java;">
/**
	 * Get data from the table.
	 */
	public ArrayList&lt;String&gt; getData(String[] keys, String selection, String[]
	  selectionArgs, String groupBy, String having, String sortBy, String sortOption){

		ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
		Cursor results = database.getAllEntries(keys, selection,
				selectionArgs, groupBy, having, sortBy, sortOption);
		while(results.moveToNext())
			list.add(results.getString(results.getColumnIndex(sortBy)));
		return list;

	}
</pre>
<p>In this example I only wanted the results to include one field, &#8220;Title&#8221;. I set the parameters for this in my main class. This returns an ArrayList, with only the column title. This is obtained by selecting the string to add to the ArrayList.</p>
<pre class="brush: java;">
list.add(results.getString(results.getColumnIndex(sortBy)));
</pre>
<p>You can use results.get[String, Integer, etc.] in order to obtain the data in a specific format. You must supply it with a column index number, which can be obtained by results.getColumnIndex(&#8220;Title&#8221;). In my case sortBy has &#8220;Title&#8221; since I will be sorting by that key value as well. As it is this code will only return the results of one column of data for many rows. Modifications can be made to return more. One way to achieve this is to create an object and return an array of those objects.</p>
<p>Once we are all done, the pipe to the database must be closed.</p>
<pre class="brush: java;">
/**
	 * Destroy the reporter.
	 * @throws Throwable
	 */
	public void destroy() throws Throwable{
        database.close();
	}
}
</pre>
<p>This attempts to close the database and returns an exception if it encounters an error.</p>
<h3><strong>DBAdapterTest.java :</strong></h3>
<p>This is the main class and will extend ListActivity in order to populate a list of the elements obtained from the database.</p>
<pre class="brush: java;">
import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class DBAdapterTest extends ListActivity {
	private ArrayList&lt;String&gt; queryString;
	private DatabaseQuery query;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        query = new DatabaseQuery(this);

        // Populate the database
        query.appendData(&quot;Title&quot;, &quot;Row One&quot;);
        query.addRow();
        query.appendData(&quot;Title&quot;, &quot;Row Two&quot;);
        query.addRow();

        // Pull the data from the database
        queryString = query.getData(new String[] {&quot;Title&quot;}, null, null, null, null, &quot;Title&quot;, &quot; ASC&quot;);
        try {
			query.destroy();
		} catch (Throwable e) {
			e.printStackTrace();
		}

        // Set the ListView
        setListAdapter(new ArrayAdapter&lt;String&gt;(this,
                android.R.layout.simple_list_item_1, queryString));
        getListView().setTextFilterEnabled(true);

    }
}
</pre>
<p>A new instance of DatabaseQuery is instantiated and data is added to the database. Once the data has been added, a query is run to pull the data out of the database and populate a ListView. This application adds the same two entries every time it is run. This is simply an quick example of how to use the DBAdapter and changes should be made depending on the needs of your application.</p>
<div id="attachment_530" class="wp-caption aligncenter" style="width: 210px"><a href="http://www.hdelossantos.com/blog/wp-content/uploads/2010/01/DBAdaptrTest.png" class="lightview" rel="gallery[518]" class="lightview" title="DBAdaptrTest"><img class="size-full wp-image-530" title="DBAdaptrTest" src="http://www.hdelossantos.com/blog/wp-content/uploads/2010/01/DBAdaptrTest.png" alt="The sorting is done alphabetically on text. Therefore &quot;Row One&quot; comes before &quot;Row Two&quot;. However, if &quot;Row Four&quot; were to be used, that would preceed the other two." width="100" height="150" /></a><p class="wp-caption-text">The sorting is done alphabetically on text. Therefore &quot;Row One&quot; comes before &quot;Row Two&quot;. However, if &quot;Row Four&quot; were to be used, that would precede the other two.</p></div>
<p>You can download the full Eclipse project folder below.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-2949674902735457";
/* 468x60, created 1/8/10 */
google_ad_slot = "5207313563";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
<a href="/school_content/sample_code/DBAdapterTest.zip"><img src="/images/download_now.png" alt="" /></a></p>

	Tags: <a href="http://www.hdelossantos.com/tag/android/" title="android" rel="tag">android</a>, <a href="http://www.hdelossantos.com/tag/database/" title="database" rel="tag">database</a>, <a href="http://www.hdelossantos.com/tag/database-adapter/" title="database adapter" rel="tag">database adapter</a>, <a href="http://www.hdelossantos.com/tag/howto/" title="howto" rel="tag">howto</a>, <a href="http://www.hdelossantos.com/tag/sqlite/" title="sqlite" rel="tag">sqlite</a>, <a href="http://www.hdelossantos.com/tag/step-by-step/" title="step-by-step" rel="tag">step-by-step</a>, <a href="http://www.hdelossantos.com/tag/tutorial/" title="tutorial" rel="tag">tutorial</a>, <a href="http://www.hdelossantos.com/tag/using-database-adapter/" title="using database adapter" rel="tag">using database adapter</a>, <a href="http://www.hdelossantos.com/tag/using-dbadapter/" title="using dbadapter" rel="tag">using dbadapter</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/" title="Creating a SQLite database in Android (December 23, 2009)">Creating a SQLite database in Android</a> (9)</li>
	<li><a href="http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/" title="Quick and easy Android HTTP POST of JSON string (December 24, 2009)">Quick and easy Android HTTP POST of JSON string</a> (4)</li>
	<li><a href="http://www.hdelossantos.com/2009/10/10/talking-twitter/" title="Talking Twitter (October 10, 2009)">Talking Twitter</a> (5)</li>
	<li><a href="http://www.hdelossantos.com/2009/11/08/ive-earned-my-android-badge/" title="I&#8217;ve earned my Android Badge :) (November 8, 2009)">I&#8217;ve earned my Android Badge :)</a> (0)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/25hSk2RDrJzuoe5p04SNgxB6dRw/0/da"><img src="http://feedads.g.doubleclick.net/~a/25hSk2RDrJzuoe5p04SNgxB6dRw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/25hSk2RDrJzuoe5p04SNgxB6dRw/1/da"><img src="http://feedads.g.doubleclick.net/~a/25hSk2RDrJzuoe5p04SNgxB6dRw/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/OqdBhCafyjs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/</feedburner:origLink></item>
		<item>
		<title>Quick and easy Android HTTP POST of JSON string</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/KL0EWNaH2jI/</link>
		<comments>http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 19:23:05 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=506</guid>
		<description><![CDATA[There are several ways to send data across the internet to a server on the Android. I was recently working on a project and needed to send a JSON string to the server to add data to a database. Additionally in certain cases I wanted to receive data back from the server. The fastest and [...]]]></description>
			<content:encoded><![CDATA[<p>There are several ways to send data across the internet to a server on the Android. I was recently working on a project and needed to send a JSON string to the server to add data to a database. Additionally in certain cases I wanted to receive data back from the server. The fastest and easiest way to do this was to use HTTP POST android library and capture the response from the server using a response handler. On the server side the response was simply generated by echoing a JSON string.<br />
<span id="more-506"></span></p>
<pre class="brush: java;">
public ArrayList&lt;String&gt; getServerData() throws JSONException, ClientProtocolException, IOException {
	    ArrayList&lt;String&gt; stringData = new ArrayList&lt;String&gt;();
	    DefaultHttpClient httpClient = new DefaultHttpClient();
		ResponseHandler &lt;String&gt; resonseHandler = new BasicResponseHandler();
		HttpPost postMethod = new HttpPost(URL_TO_PHP_FILE_TO_HANDLE_POST);
		List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put(&quot;someKey&quot;, someData); //Data being sent to the server, which should produce a reply

		nameValuePairs.add(new BasicNameValuePair(&quot;jsonString&quot;, jsonObject.toString()));
		postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		String response = httpClientexecute(postMethod,resonseHandler);

		JSONObject jsonResponse = new JSONObject(response);

		JSONArray serverData1 = jsonResponse.getJSONArray(&quot;data1&quot;);
		JSONArray serverData2 = jsonResponse.getJSONArray(&quot;data2&quot;);
		for(int i = 0; i &lt; serverData1.length() &amp;&amp; i &lt; serverData2.length(); i++) {
			//Do something with the data
		}

		return //the data;
   }
</pre>
<p>The code above shows the receipt of those two JSON encoded arrays. In my case I had to get a little creative with the server side code since I wanted to send two arrays encoded in JSON. However, the PHP library&#8217;s JSON encoding differs from that of Android so I had to encode the two arrays I needed to send using loops. </p>
<pre class="brush: plain;">
// Android expects to receive JSON arrays like so
{&quot;array_name&quot;:[data, data1, data2], &quot;array2_name&quot;:[data, data1, data2]}
</pre>
<p>The PHP code I wrote to format my arrays in a JSON format Android would understand is below.</p>
<pre class="brush: php;">
// Create the JSON string
        while($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
            $data1[] = $row['data1'];
            $data2[] = $row['data2'];
        }

        mysql_close($handle);

        $json = '{&quot;data1&quot;:[';

        for($i = 0; $i &lt; sizeof($data1); $i++) {
            $json = $json . $data1[$i];

            if($i &lt; sizeof($data1) - 1)
                $json = $json . ',';
        }

        $json = $json . '],&quot;data2&quot;:[';

        for($i = 0; $i &lt; sizeof($data2); $i++) {
            $json = $json . $data2[$i];

             if($i &lt; sizeof($data2) - 1)
                $json = $json . ',';
        }

        $json = $json . ']}';

        // Send the client a JSON string with the result
        echo ($json);
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "pub-2949674902735457";
/* 468x60, created 1/8/10 */
google_ad_slot = "5207313563";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

	Tags: <a href="http://www.hdelossantos.com/tag/android/" title="android" rel="tag">android</a>, <a href="http://www.hdelossantos.com/tag/database/" title="database" rel="tag">database</a>, <a href="http://www.hdelossantos.com/tag/howto/" title="howto" rel="tag">howto</a>, <a href="http://www.hdelossantos.com/tag/http/" title="http" rel="tag">http</a>, <a href="http://www.hdelossantos.com/tag/java/" title="java" rel="tag">java</a>, <a href="http://www.hdelossantos.com/tag/json/" title="JSON" rel="tag">JSON</a>, <a href="http://www.hdelossantos.com/tag/mysql/" title="mysql" rel="tag">mysql</a>, <a href="http://www.hdelossantos.com/tag/php/" title="PHP" rel="tag">PHP</a>, <a href="http://www.hdelossantos.com/tag/post/" title="POST" rel="tag">POST</a>, <a href="http://www.hdelossantos.com/tag/server/" title="server" rel="tag">server</a>, <a href="http://www.hdelossantos.com/tag/tutorial/" title="tutorial" rel="tag">tutorial</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/" title="Using a SQLite Database in Android (January 7, 2010)">Using a SQLite Database in Android</a> (8)</li>
	<li><a href="http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/" title="Creating a SQLite database in Android (December 23, 2009)">Creating a SQLite database in Android</a> (9)</li>
	<li><a href="http://www.hdelossantos.com/2009/10/10/talking-twitter/" title="Talking Twitter (October 10, 2009)">Talking Twitter</a> (5)</li>
	<li><a href="http://www.hdelossantos.com/2009/11/08/ive-earned-my-android-badge/" title="I&#8217;ve earned my Android Badge :) (November 8, 2009)">I&#8217;ve earned my Android Badge :)</a> (0)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/5iy9L_vvIiH9csym8_ELA-3NgzI/0/da"><img src="http://feedads.g.doubleclick.net/~a/5iy9L_vvIiH9csym8_ELA-3NgzI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/5iy9L_vvIiH9csym8_ELA-3NgzI/1/da"><img src="http://feedads.g.doubleclick.net/~a/5iy9L_vvIiH9csym8_ELA-3NgzI/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/KL0EWNaH2jI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/</feedburner:origLink></item>
		<item>
		<title>Creating a SQLite database in Android</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/_c9twvXMfyM/</link>
		<comments>http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 07:40:49 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database adapter]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[step-by-step]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=477</guid>
		<description><![CDATA[This example will show you how to create a somewhat abstracted SQLite adapter on Android. This adapter can then be utilized by your program to do common database functions such as, querying and searching. I start by creating the class DBAdapter in my Android project and declaring the variable data necessary to create the database.
EDIT: [...]]]></description>
			<content:encoded><![CDATA[<p>This example will show you how to create a somewhat abstracted SQLite adapter on Android. This adapter can then be utilized by your program to do common database functions such as, querying and searching. I start by creating the class DBAdapter in my Android project and declaring the variable data necessary to create the database.</p>
<p><span style="color: #ff0000;">EDIT: The code has been modified since it originally assumed that a key option would be passed for every key. It will now work if no key options are passed. Additionally, &#8220;null&#8221; can also be passed to it if no key options are desired.</span></p>
<p><span id="more-477"></span></p>
<pre class="brush: java;">
public class DBAdapter{

	private static final String DATABASE_NAME = &quot;example.db&quot;;
	private String DATABASE_TABLE;

	private static final int DATABASE_VERSION = 1;
</pre>
<p><strong>DATABASE_NAME</strong> is of course the name of the database we will be creating. This is usually done one database per program. The database can be found in /data/data/<br />
/databases/.<br />
<strong>DATABASE_TABLE</strong> will be the name of the table you will be creating. We will make it so that wen a new instance of the database is created, the table name has to be passed so that new tables can be created without the need to create a new class, or creating static table assignments.<br />
<strong>DATABASE_VERSION</strong> is the version of the database we will be creating; 1 is fine here.</p>
<p>Now we must create the variables to set our table structure.</p>
<pre class="brush: java;">
// Index Key column
public static final String KEY_ID = &quot;_id&quot;;

// Name of the column index of each column in DB
public  ArrayList&lt;String&gt; TABLE_KEYS =  new ArrayList&lt;String&gt;();
public  ArrayList&lt;String&gt; TABLE_OPTIONS = new ArrayList&lt;String&gt;();
public  final String KEY_TIMESTAMP = &quot;timeStamp&quot;;
public  final int TIMESTAMP_COLUMN = 1;
</pre>
<p>We first create our primary key value which will have the row numbers of the data entered in our table. This is the <strong>KEY_ID</strong> string, which contains &#8220;_id&#8221;. The actual column heading that will show up on the table will be &#8220;_id&#8221;. In order to abstract this helper as much as possible, the keys and options for the keys will be passed in as ArrayLists of string objects from the class that calls the DBAdapter. <strong>TABLE_KEYS</strong> refers to the column name, and <strong>TABLE_OPTIONS</strong> refers to the options for that column (these can be &#8220;text not null&#8221;, setting the column type to &#8220;integer&#8221;, etc.). I always like creating a column which contains a timestamp in case I want to sort the data by time, which is what the <strong>KEY_TIMESTAMP</strong> is. <strong>TIMESTAMP_COLUMN</strong> sets the column number of the timestamp column to 1, which makes it easier to select data later on. This is not necessary since you can get the column numbers by searching for the column name (I&#8217;ll go over this later).</p>
<pre class="brush: java;">
// Create new database
	private String DATABASE_CREATE;

	// Variable to hold database instant
	private SQLiteDatabase db;

	// Database open/upgrade helper
	private myDBHelper dbHelper;
</pre>
<p><strong>DATABASE_CREATE</strong> This variable will contain the string we will use to create the database. This is where we will set our parameters and key names.<br />
<strong>db</strong> is the database instance we will create.<br />
<strong>dbHelper</strong> is an instance of the class myDBHelper which we will create later within this class. This is what actually initiates the database and creates tables if needed, etc. (This extends SQLiteOpenHelper).</p>
<pre class="brush: java;">
	public DBAdapter(Context context, String table, ArrayList&lt;String&gt; keys, ArrayList&lt;String&gt; options){
		// Start initializing all of the variables
		DATABASE_TABLE = table;
		TABLE_KEYS = (ArrayList&lt;String&gt;)keys.clone();
		TABLE_OPTIONS = options;

		String keyString = &quot;&quot;;
		for(int i = 0; TABLE_KEYS.size() &gt; i; i++){

			// Add commas to the options elements if there is a next value.
			if(i + 1 &lt; TABLE_OPTIONS.size() &amp;&amp; TABLE_OPTIONS.get(i) != null){
				TABLE_OPTIONS.set(i, TABLE_OPTIONS.get(i) + &quot;,&quot;);
			}else if (i + 1 == TABLE_OPTIONS.size() &amp;&amp; TABLE_OPTIONS.get(i) != null) {
				if(i + 1 &lt; TABLE_KEYS.size()){
					TABLE_OPTIONS.set(i, TABLE_OPTIONS.get(i) + &quot;,&quot;);
				}else {
					TABLE_KEYS.set(i, TABLE_KEYS.get(i) + &quot;&quot;);
				}
			}else if (i + 1 != TABLE_KEYS.size()) {
				TABLE_KEYS.set(i, TABLE_KEYS.get(i) + &quot;,&quot;);
			}else {
				TABLE_KEYS.set(i, TABLE_KEYS.get(i) + &quot;&quot;);
			}

			System.out.println(TABLE_OPTIONS.toString());
			System.out.println(TABLE_KEYS.toString());

			if(i + 1 &lt;= TABLE_OPTIONS.size() &amp;&amp; TABLE_OPTIONS.get(i) != null)
				keyString = keyString + &quot; &quot; + TABLE_KEYS.get(i) + &quot; &quot; + TABLE_OPTIONS.get(i);
			else if(i + 1 &gt; TABLE_OPTIONS.size() || TABLE_OPTIONS.get(i) == null){
				keyString = keyString + &quot; &quot; + TABLE_KEYS.get(i);
			}
		}

		// Create the database creation string.
		DATABASE_CREATE = &quot;CREATE TABLE IF NOT EXISTS &quot; + DATABASE_TABLE + &quot; (&quot;
		+ &quot;_id&quot; + &quot; INTEGER PRIMARY KEY AUTOINCREMENT, &quot; + KEY_TIMESTAMP + &quot;,&quot; + keyString + &quot;);&quot;;

		// Create a new Helper
		dbHelper = new myDBHelper(context, DATABASE_NAME, null, DATABASE_VERSION,
				DATABASE_TABLE, DATABASE_CREATE);
	}
</pre>
<p>This is the constructor for DBAdapter, which sets up all of the variables for further calls to other methods in this class. This opens the database if it exists or create it if it doesn&#8217;t. Additionally checks if the<br />
table exists and creates it if it doesn&#8217;t. The ArrayLists of string objects for the key names and options are parsed, and commas are added where they need to be so that the <strong>DATABASE_CREATE</strong> creation string can be created. A clone of the keys ArrayList is created so that the changes we make (adding commas at the end of options and keys if there will be something following them) here will no affect the variable when we call it later. The last thing we do is instantiate the database by calling our dbHelper, which is the actual function that creates the database with the parameters which we have given it in our creation string, the database name, table name, etc.).</p>
<pre class="brush: java;">
public DBAdapter open() throws SQLException {
		db = dbHelper.getWritableDatabase();
		return this;
	}

public void close() {
		db.close();
	}
</pre>
<p>These function allow opening and closing of the database. It is necessary to open the database before data can be written or read from it. Likewise it is necessary to close the database once one has finished with it, otherwise memory leaks occur.</p>
<pre class="brush: java;">
public long insertEntry(ArrayList&lt;String&gt; key, ArrayList&lt;String&gt; value) {
		String timeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()).toString();
		ContentValues contentValues = new ContentValues();
		for(int i = 0; key.size() &gt; i; i++){
			contentValues.put(key.get(i), value.get(i));
		}
		contentValues.put(KEY_TIMESTAMP, timeStamp);
		return db.insert(DATABASE_TABLE, null, contentValues);
	}
</pre>
<p>This method is used to insert and entry into the database. It takes in two variables of ArraList of string objects which contain the column names or keys and the data to be added into each key. When an entry is inserted this method also sets the timestamp value automatically.</p>
<pre class="brush: java;">
public boolean removeEntry(long rowIndex) {
		return db.delete(DATABASE_TABLE, KEY_ID + &quot;=&quot; + rowIndex, null) &gt; 0;
	}
</pre>
<p>This method removes a row of data from the database. The <strong>rowIndex</strong> must be provided. This can be acquired by running a query and getting the <strong>_id</strong> field from the result.</p>
<pre class="brush: java;">
public Cursor getAllEntries(String[] columns, String selection, String[] selectionArgs,
			String groupBy, String having, String sortBy, String sortOption) {
		return db.query(DATABASE_TABLE, columns, selection, selectionArgs, groupBy,
				having, sortBy + &quot; &quot; + sortOption);
	}
</pre>
<p>This method runs a query and returns a cursor through all of the matching results.<br />
<strong>columns</strong> is an string array of columns to be included in the result.<br />
<strong>selection</strong> is the value to look for in the columns. A null will return all results.<br />
<strong>selectionArgs</strong> is a string array of arguments for the selection. Can be null.<br />
<strong>groupBy</strong> option to group the results by. Can be set to null.<br />
<strong>having</strong> a filter declare which row groups to include in the cursor. Can be null.<br />
<strong>sortBy</strong> column to sort the results by.<br />
<strong>sortOption</strong> is how to sort the results, ASC for ascending, DESC for descending.</p>
<pre class="brush: java;">
public int updateEntry(long rowIndex, ArrayList&lt;String&gt; key, ArrayList&lt;String&gt; value) {
		String timeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()).toString();
		String where = KEY_ID + &quot;=&quot; + rowIndex;
		ContentValues contentValues = new ContentValues();
		for(int i = 0; key.size() &gt; i; i++){
			contentValues.put(key.get(i), value.get(i));
		}
		contentValues.put(KEY_TIMESTAMP, timeStamp);
		return db.update(DATABASE_TABLE, contentValues, where, null);
	}
</pre>
<p>This method updates a row in the database. This takes in the same parameters as the method to insert a new row, with the additional rowIndex variable, which is the number of the row to update.</p>
<pre class="brush: java;">
public boolean clearTable() {
		return db.delete(DATABASE_TABLE, null, null) &gt; 0;
	}
</pre>
<p>I&#8217;m not particularly fond of this method since it can cause more harm than good. However, I think that it&#8217;s good to have it for testing purposes. This of course clears all of the contents of a table.</p>
<pre class="brush: java;">
private static class myDBHelper extends SQLiteOpenHelper {
		private String creationString;
		private String tableName;
		@SuppressWarnings(&quot;unused&quot;)
		SQLiteDatabase db;

		/**
		 * Creates a myDBHelper object.
		 * @param context The context where the access is needed
		 * @param name Name of database file
		 * @param factory A CursorFactory, or null to use default CursorFactory
		 * @param version Database version
		 * @param tableName Name of table within database
		 * @param creationString SQL String used to create the database
		 */
		public myDBHelper(Context context, String name, CursorFactory factory,
				int version, String tableName, String creationString) {
			super(context, name, factory, version);
			this.creationString = creationString;
			this.tableName = tableName;
		}

		/**
		 * Creates the database table.
		 * @param db The database used by this helper to create the table in
		 */
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(creationString);
		}

		/**
		 * This method determines if the database needs to be updated or not.
		 * @param db The database used by this helper
		 * @param oldVersion The old database version
		 * @param newVersion The new database version
		 */
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// Log the version upgrade
			Log.w(&quot;TaskDBAdapter&quot;, &quot;Upgrading from version &quot; + oldVersion +
					&quot; to &quot; + newVersion + &quot;, which will destroy all old data&quot;);

			db.execSQL(&quot;DROP TABLE IF EXISTS &quot; + tableName);
			onCreate(db);

		}

		/**
		 * Creates tables when the database is opened if the tables need to be created.
		 * @param db The database used by this helper
		 */
		@Override
		public void onOpen(SQLiteDatabase db) {
			db.execSQL(creationString);
		}

	}
}
</pre>
<p>This subclass is a helper for DBAdapter and does the job of creating the database and checking if the database needs an upgrade to new version depending on version number specified by DBAdapter.</p>
<p>For instructions on using this database adapter please continue to <a href="/2010/01/07/using-a-sqlite-database-in-android/">&#8220;Using a SQLite Database in Android&#8221;</a></p>
<p>You can download the full code below.</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-2949674902735457";
/* 468x60, created 1/8/10 */
google_ad_slot = "5207313563";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
<a href="/school_content/sample_code/DBAdapter.java"><img src="/images/download_now.png" alt="" /></a></p>

	Tags: <a href="http://www.hdelossantos.com/tag/android/" title="android" rel="tag">android</a>, <a href="http://www.hdelossantos.com/tag/database/" title="database" rel="tag">database</a>, <a href="http://www.hdelossantos.com/tag/database-adapter/" title="database adapter" rel="tag">database adapter</a>, <a href="http://www.hdelossantos.com/tag/howto/" title="howto" rel="tag">howto</a>, <a href="http://www.hdelossantos.com/tag/sqlite/" title="sqlite" rel="tag">sqlite</a>, <a href="http://www.hdelossantos.com/tag/step-by-step/" title="step-by-step" rel="tag">step-by-step</a>, <a href="http://www.hdelossantos.com/tag/tutorial/" title="tutorial" rel="tag">tutorial</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/" title="Using a SQLite Database in Android (January 7, 2010)">Using a SQLite Database in Android</a> (8)</li>
	<li><a href="http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/" title="Quick and easy Android HTTP POST of JSON string (December 24, 2009)">Quick and easy Android HTTP POST of JSON string</a> (4)</li>
	<li><a href="http://www.hdelossantos.com/2009/10/10/talking-twitter/" title="Talking Twitter (October 10, 2009)">Talking Twitter</a> (5)</li>
	<li><a href="http://www.hdelossantos.com/2009/11/08/ive-earned-my-android-badge/" title="I&#8217;ve earned my Android Badge :) (November 8, 2009)">I&#8217;ve earned my Android Badge :)</a> (0)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/TB04seChVgCexCFwwSJ5uywdszc/0/da"><img src="http://feedads.g.doubleclick.net/~a/TB04seChVgCexCFwwSJ5uywdszc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/TB04seChVgCexCFwwSJ5uywdszc/1/da"><img src="http://feedads.g.doubleclick.net/~a/TB04seChVgCexCFwwSJ5uywdszc/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/_c9twvXMfyM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/</feedburner:origLink></item>
		<item>
		<title>I’ve earned my Android Badge :)</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/MIvIZdS-1E4/</link>
		<comments>http://www.hdelossantos.com/2009/11/08/ive-earned-my-android-badge/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 04:13:07 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[SHPE]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=467</guid>
		<description><![CDATA[After having been developing Android applications for 2 months I like to think that I have earned my Android badge. Last week at the SHPE conference I was given an android sticker at the Google booth, which now adorns my laptop.

Of course calling myself a developer makes me think of:



	Tags: android, developer, google, SHPE

	Related posts
	
	Using [...]]]></description>
			<content:encoded><![CDATA[<p>After having been developing Android applications for 2 months I like to think that I have earned my Android badge. Last week at the <a href="http://oneshpe.shpe.org/wps/portal/national">SHPE</a> conference I was given an android sticker at the Google booth, which now adorns my laptop.</p>
<p><a href="http://www.hdelossantos.com/blog/wp-content/uploads/2009/11/DSC01505-1024x768.jpg" class="lightview" rel="gallery[467]" class="lightview" title="My Laptop&#039;s Android"><img src="http://www.hdelossantos.com/blog/wp-content/uploads/2009/11/DSC01505-300x225.jpg" alt="My Laptop&#039;s Android" title="My Laptop&#039;s Android" width="300" height="225" class="aligncenter size-large wp-image-468" /></a></p>
<p>Of course calling myself a <em>developer</em> makes me think of:</p>
<div align="center"><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/8zEQhhaJsU4&#038;hl=en&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/8zEQhhaJsU4&#038;hl=en&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></div>
<p></p>

	Tags: <a href="http://www.hdelossantos.com/tag/android/" title="android" rel="tag">android</a>, <a href="http://www.hdelossantos.com/tag/developer/" title="developer" rel="tag">developer</a>, <a href="http://www.hdelossantos.com/tag/google/" title="google" rel="tag">google</a>, <a href="http://www.hdelossantos.com/tag/shpe/" title="SHPE" rel="tag">SHPE</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/" title="Using a SQLite Database in Android (January 7, 2010)">Using a SQLite Database in Android</a> (8)</li>
	<li><a href="http://www.hdelossantos.com/2009/10/10/talking-twitter/" title="Talking Twitter (October 10, 2009)">Talking Twitter</a> (5)</li>
	<li><a href="http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/" title="Quick and easy Android HTTP POST of JSON string (December 24, 2009)">Quick and easy Android HTTP POST of JSON string</a> (4)</li>
	<li><a href="http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/" title="Creating a SQLite database in Android (December 23, 2009)">Creating a SQLite database in Android</a> (9)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/StaACSvHMPd4xLtRMdhFoUcwc2c/0/da"><img src="http://feedads.g.doubleclick.net/~a/StaACSvHMPd4xLtRMdhFoUcwc2c/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/StaACSvHMPd4xLtRMdhFoUcwc2c/1/da"><img src="http://feedads.g.doubleclick.net/~a/StaACSvHMPd4xLtRMdhFoUcwc2c/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/MIvIZdS-1E4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/11/08/ive-earned-my-android-badge/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/11/08/ive-earned-my-android-badge/</feedburner:origLink></item>
		<item>
		<title>It’s that time of the year again.</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/5yK_M4TkeuE/</link>
		<comments>http://www.hdelossantos.com/2009/10/11/its-that-time-of-the-year-again/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 16:32:23 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[The Wisconsin Experience]]></category>
		<category><![CDATA[cold]]></category>
		<category><![CDATA[snow]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=458</guid>
		<description><![CDATA[
	Tags: cold, snow, The Wisconsin Experience

	Related posts
	
	Snowflake!!! (0)
	Ready for an expedition to the South Pole (0)
	I Hate the Rain! (0)
	Wish I were Home (0)
	Wintry mix? (0)


]]></description>
			<content:encoded><![CDATA[<div id="attachment_459" class="wp-caption aligncenter" style="width: 510px"><img src="http://www.hdelossantos.com/blog/wp-content/uploads/2009/10/weather.png" alt="Here comes the snow." title="Weather 10/11/2009" width="500" height="70" class="size-full wp-image-459" /><p class="wp-caption-text">Here comes the snow.</p></div>

	Tags: <a href="http://www.hdelossantos.com/tag/cold/" title="cold" rel="tag">cold</a>, <a href="http://www.hdelossantos.com/tag/snow/" title="snow" rel="tag">snow</a>, <a href="http://www.hdelossantos.com/tag/wisconsin/" title="The Wisconsin Experience" rel="tag">The Wisconsin Experience</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2008/11/11/snowflake/" title="Snowflake!!! (November 11, 2008)">Snowflake!!!</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2008/12/01/ready-for-an-expedition-to-the-south-pole/" title="Ready for an expedition to the South Pole (December 1, 2008)">Ready for an expedition to the South Pole</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/03/08/i-hate-the-rain/" title="I Hate the Rain! (March 8, 2009)">I Hate the Rain!</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/03/12/wish-i-were-home/" title="Wish I were Home (March 12, 2009)">Wish I were Home</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2008/11/11/wintry-mix/" title="Wintry mix? (November 11, 2008)">Wintry mix?</a> (0)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/6h5VI8QLXMuZoEMvWNvUAgMlZPI/0/da"><img src="http://feedads.g.doubleclick.net/~a/6h5VI8QLXMuZoEMvWNvUAgMlZPI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/6h5VI8QLXMuZoEMvWNvUAgMlZPI/1/da"><img src="http://feedads.g.doubleclick.net/~a/6h5VI8QLXMuZoEMvWNvUAgMlZPI/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/5yK_M4TkeuE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/10/11/its-that-time-of-the-year-again/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/10/11/its-that-time-of-the-year-again/</feedburner:origLink></item>
		<item>
		<title>Talking Twitter</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/uHDS6zTdjB0/</link>
		<comments>http://www.hdelossantos.com/2009/10/10/talking-twitter/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 05:58:43 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Computer Engineering]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Sample Work]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[code assignment]]></category>
		<category><![CDATA[device programming]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mobile device]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[speech-to-text]]></category>
		<category><![CDATA[text-to-speech]]></category>
		<category><![CDATA[text2speech]]></category>
		<category><![CDATA[TTS library]]></category>
		<category><![CDATA[tweet]]></category>
		<category><![CDATA[tweets]]></category>
		<category><![CDATA[twitta]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=437</guid>
		<description><![CDATA[A week ago, for my mobile device programming class, I had to add text-to-speech and speech-to-text capabilities to a freely available Android program called Twitta. The features I added were very crudely superimposed on the Twitta interface, therefore this edit is by no means polished or intended for production usage.
There are 3 button &#8220;S&#8221;, &#8220;X&#8221;, [...]]]></description>
			<content:encoded><![CDATA[<p>A week ago, for my mobile device programming class, I had to add text-to-speech and speech-to-text capabilities to a freely available Android program called <a href="http://code.google.com/p/twitta/">Twitta</a>. The features I added were very crudely superimposed on the Twitta interface, therefore this edit is by no means polished or intended for production usage.</p>
<p>There are 3 button &#8220;S&#8221;, &#8220;X&#8221;, and &#8220;R&#8221;. &#8220;S&#8221; starts the playback of all of the tweets which are currently displayed on the screen. Once the user scrolls down and new tweets appear on the screen the button can be pressed again and only the new ones will be read. &#8220;X&#8221; stops the playback of the messages. &#8220;R&#8221; prompts the user to speak their tweet. The google speech to text engine converts it to text and is displayed on the edit bar. If the message was wrong, pressing &#8220;R&#8221; again clears it and prompts for new speech. The message can also be edited with the keyboard. Below is a video of the application in action:</p>
<div align="center">
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/gnMUc1TuxpE&#038;hl=en&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/gnMUc1TuxpE&#038;hl=en&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></div>
<p><span id="more-437"></span></p>
<p>The source code is below. The sections edited by me are enclosed in comments.</p>
<pre class="brush: plain;">
/*
 * Copyright (C) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dart.android.twitter;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.*;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.dart.android.twitter.TwitterApi.ApiException;
import com.dart.android.twitter.TwitterApi.AuthException;
import com.google.android.photostream.UserTask;
import com.google.tts.TTS;
import com.google.tts.TTS.InitListener;

public class TwitterActivity extends BaseActivity implements InitListener{
  private static final String TAG = &quot;TwitterActivity&quot;;

  //BEGIN: Added by Hanly De Los Santos
  //Speech
  private static boolean ttsReady = false;
  private static TTS myTTS;
  private static ConcurrentLinkedQueue&lt;String&gt; tweetStrings;
  private Button speak;
  private Button stop;
  private Button reco;
  private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
  //END: Added by Hanly De Los Santos

  // Views.
  private ListView mTweetList;
  private TweetAdapter mTweetAdapter;

  private TweetEdit mTweetEdit;
  private ImageButton mSendButton;

  private TextView mProgressText;

  // State.
  private int mState;

  private static final int STATE_ALL = 0;
  private static final int STATE_REPLIES = 1;

  // Tasks.
  private UserTask&lt;Void, Void, RetrieveResult&gt; mRetrieveTask;
  private UserTask&lt;Void, Void, SendResult&gt; mSendTask;
  private UserTask&lt;Void, Void, RetrieveResult&gt; mFollowersRetrieveTask;

  // Refresh data at startup if last refresh was this long ago or greater.
  private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;

  // Refresh followers if last refresh was this long ago or greater.
  private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;

  private static final String LAUNCH_ACTION = &quot;com.dart.android.twitter.TWEETS&quot;;
  private static final String NEW_TWEET_ACTION = &quot;com.dart.android.twitter.NEW&quot;;

  private static final String EXTRA_TEXT = &quot;text&quot;;

  public static Intent createIntent(Context context) {
    Intent intent = new Intent(LAUNCH_ACTION);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    return intent;
  }

  public static Intent createNewTaskIntent(Context context) {
    Intent intent = createIntent(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    return intent;
  }

  public static Intent createNewTweetIntent(String text) {
    Intent intent = new Intent(NEW_TWEET_ACTION);
    intent.putExtra(EXTRA_TEXT, text);

    return intent;
  }

  private boolean isReplies() {
    return mState == STATE_REPLIES;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //BEGIN: Added by Hanly De Los Santos

    //Initialize TTS Service
    myTTS = new TTS(this, this, true);
    tweetStrings = new ConcurrentLinkedQueue&lt;String&gt;();

    //END: Added by Hanly De Los Santos

    if (!getApi().isLoggedIn()) {
      Log.i(TAG, &quot;Not logged in.&quot;);
      handleLoggedOut();
      return;
    }

    setContentView(R.layout.main);

    Intent intent = getIntent();
    String action = intent.getAction();

    mState = mPreferences.getInt(
        Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL);

    mTweetList = (ListView) findViewById(R.id.tweet_list);

    mTweetEdit = new TweetEdit((EditText) findViewById(R.id.tweet_edit),
        (TextView) findViewById(R.id.chars_text));
    mTweetEdit.setOnKeyListener(tweetEnterHandler);

    if (NEW_TWEET_ACTION.equals(action)) {
      mTweetEdit.setText(intent.getStringExtra(EXTRA_TEXT));
    }

    mProgressText = (TextView) findViewById(R.id.progress_text);

    mSendButton = (ImageButton) findViewById(R.id.send_button);
    mSendButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        doSend();
      }
    });

    //BEGIN: Added by Hanly De Los Santos
    // Speak Button
    this.speak = (Button)this.findViewById(R.id.Speak);
    this.speak.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
			if(tweetStrings != null){
				new Thread(new Runnable(){
	        		public void run(){
		        		try{
		        			Speak startSpeak = new Speak();
		        	        while(!myTTS.isSpeaking()){
		        	        	for(int i=0; i&lt;tweetStrings.size(); i++){
		        	        		String speak = (String)tweetStrings.poll();
		        		        	startSpeak.speak(ttsReady, myTTS, speak);
		        		        	final String TAG = &quot;Hanly-Pop Out&quot;;
		        		            Log.v(TAG, speak);
		        		        }
		        	        }
		        		}
		        		catch(Exception e){}
	        		}
	        	}).start();
		    }
		}
    });

    this.stop = (Button)this.findViewById(R.id.Stop);
    this.stop.setOnClickListener(new OnClickListener() {

    	@Override
		public void onClick(View v) {
			Speak startSpeak = new Speak();
			startSpeak.stop(ttsReady, myTTS);
		}
    });

    //Start of speech recognition code
    this.reco = (Button)this.findViewById(R.id.Reco);
    this.reco.setOnClickListener(new OnClickListener(){

    	@Override
		public void onClick(View v) {
    		startVoiceRecognitionActivity();
		}
    });
    //END: Added by Hanly De Los Santos

    // Mark all as read.
    getDb().markAllTweetsRead();

    setupState();

    registerForContextMenu(mTweetList);

    boolean shouldRetrieve = false;

    long lastRefreshTime = mPreferences.getLong(
        Preferences.LAST_TWEET_REFRESH_KEY, 0);
    long nowTime = Utils.getNowTime();

    long diff = nowTime - lastRefreshTime;
    Log.i(TAG, &quot;Last refresh was &quot; + diff + &quot; ms ago.&quot;);

    if (diff &gt; REFRESH_THRESHOLD) {
      shouldRetrieve = true;
    } else if (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
      // Check to see if it was running a send or retrieve task.
      // It makes no sense to resend the send request (don't want dupes)
      // so we instead retrieve (refresh) to see if the message has posted.
      Log.i(TAG, &quot;Was last running a retrieve or send task. Let's refresh.&quot;);
      shouldRetrieve = true;
    }

    if (shouldRetrieve) {
      doRetrieve();
    }

    long lastFollowersRefreshTime = mPreferences.getLong(
        Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);

    diff = nowTime - lastFollowersRefreshTime;
    Log.i(TAG, &quot;Last followers refresh was &quot; + diff + &quot; ms ago.&quot;); 

    if (diff &gt; FOLLOWERS_REFRESH_THRESHOLD) {
      doRetrieveFollowers();
    }
  }

//BEGIN: Added by Hanly De Los Santos
  private void startVoiceRecognitionActivity() {
	  mTweetEdit.setText(&quot;&quot;);
	  Intent intent = new Intent(&quot;android.speech.action.RECOGNIZE_SPEECH&quot;);
	  startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == VOICE_RECOGNITION_REQUEST_CODE &amp;&amp; resultCode == RESULT_OK) {
          // Fill the list view with the strings the recognizer thought it could have heard
          ArrayList&lt;String&gt; matches = data.getStringArrayListExtra(
                  RecognizerIntent.EXTRA_RESULTS);
          try{
        	  Thread.currentThread().sleep(1000);//sleep for 1000 ms
        	}
        	catch(Exception ie){
        	//If this thread was interrupted by another thread
        	}
    	  Speak startSpeak = new Speak();
          String speak = &quot;Did you say &quot;+matches.toString();
          startSpeak.speak(ttsReady, myTTS, speak);
          mTweetEdit.setTextAndFocus(matches.toString().replaceAll(&quot;[\\]\\[]&quot;, &quot;&quot;));
          final String TAG = &quot;Hanly-Speak Result&quot;;
          Log.v(TAG, matches.toString());
      }

      super.onActivityResult(requestCode, resultCode, data);
  }
	//END: Added by Hanly De Los Santos
  @Override
  protected void onResume() {
    super.onResume();

    if (!getApi().isLoggedIn()) {
      Log.i(TAG, &quot;Not logged in.&quot;);
      handleLoggedOut();
      return;
    }
  }

  private void doRetrieveFollowers() {
    Log.i(TAG, &quot;Attempting followers retrieve.&quot;);

    if (mFollowersRetrieveTask != null
        &amp;&amp; mFollowersRetrieveTask.getStatus() == UserTask.Status.RUNNING) {
      Log.w(TAG, &quot;Already retrieving.&quot;);
    } else {
      mFollowersRetrieveTask = new FollowersTask().execute();
    }
  }

  private static final String SIS_RUNNING_KEY = &quot;running&quot;;

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (mRetrieveTask != null
        &amp;&amp; mRetrieveTask.getStatus() == UserTask.Status.RUNNING) {
      outState.putBoolean(SIS_RUNNING_KEY, true);
    } else if (mSendTask != null
        &amp;&amp; mSendTask.getStatus() == UserTask.Status.RUNNING) {
      outState.putBoolean(SIS_RUNNING_KEY, true);
    }
  }

  @Override
  protected void onRestoreInstanceState(Bundle bundle) {
    super.onRestoreInstanceState(bundle);

    mTweetEdit.updateCharsRemain();
  }

  @Override
  protected void onDestroy() {
    Log.i(TAG, &quot;onDestroy.&quot;);

    if (mSendTask != null &amp;&amp; mSendTask.getStatus() == UserTask.Status.RUNNING) {
      // Doesn't really cancel execution (we let it continue running).
      // See the SendTask code for more details.
      mSendTask.cancel(true);
    }

    if (mRetrieveTask != null
        &amp;&amp; mRetrieveTask.getStatus() == UserTask.Status.RUNNING) {
      mRetrieveTask.cancel(true);
    }

    // Don't need to cancel FollowersTask (assuming it ends properly).

    super.onDestroy();
  }

  // UI helpers.

  private void updateProgress(String progress) {
    mProgressText.setText(progress);
  }

  private void setupState() {
    Cursor cursor;

    if (isReplies()) {
      cursor = getDb().fetchReplies();
      setTitle(&quot;@&quot; + getApi().getUsername());
    } else {
      cursor = getDb().fetchAllTweets();
      setTitle(R.string.app_name);
    }

    startManagingCursor(cursor);

    mTweetAdapter = new TweetAdapter(this, cursor);
    mTweetList.setAdapter(mTweetAdapter);
  }

  private static final int CONTEXT_MORE_ID = 3;
  private static final int CONTEXT_REPLY_ID = 0;
  private static final int CONTEXT_RETWEET_ID = 1;
  private static final int CONTEXT_DM_ID = 2;

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    Cursor cursor = (Cursor) mTweetAdapter.getItem(info.position);
    long userId = cursor.getLong(cursor
        .getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER_ID));
    String user = cursor.getString(cursor
        .getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER));

    menu.add(0, CONTEXT_MORE_ID, 0, user);
    menu.add(0, CONTEXT_REPLY_ID, 0, R.string.reply);
    menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.retweet);

    MenuItem item = menu.add(0, CONTEXT_DM_ID, 0, R.string.dm);
    item.setEnabled(getDb().isFollower(userId));
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    Cursor cursor = (Cursor) mTweetAdapter.getItem(info.position);

    if (cursor == null) {
      Log.w(TAG, &quot;Selected item not available.&quot;);
      return super.onContextItemSelected(item);
    }

    switch (item.getItemId()) {
    case CONTEXT_MORE_ID:
      String who = cursor.getString(
          cursor.getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER));
      launchActivity(UserActivity.createIntent(who));

      return true;
    case CONTEXT_REPLY_ID:
      int userIndex = cursor.getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER);
      // TODO: this isn't quite perfect. It leaves extra empty spaces if you
      // perform the reply action again.
      String replyTo = &quot;@&quot; + cursor.getString(userIndex);
      String text = mTweetEdit.getText();
      text = replyTo + &quot; &quot; + text.replace(replyTo, &quot;&quot;);
      mTweetEdit.setTextAndFocus(text);

      return true;
    case CONTEXT_RETWEET_ID:
      String retweet = &quot;RT @&quot;
          + cursor.getString(cursor
              .getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER))
          + &quot; &quot;
          + cursor.getString(cursor
              .getColumnIndexOrThrow(TwitterDbAdapter.KEY_TEXT));
      mTweetEdit.setTextAndFocus(retweet);

      return true;
    case CONTEXT_DM_ID:
      String user = cursor.getString(cursor
          .getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER));
      launchActivity(DmActivity.createIntent(user));
      return true;
    default:
      return super.onContextItemSelected(item);
    }
  }

  private static class TweetAdapter extends CursorAdapter {

    public TweetAdapter(Context context, Cursor cursor) {
      super(context, cursor);

      mInflater = LayoutInflater.from(context);

      mUserTextColumn = cursor.getColumnIndexOrThrow(TwitterDbAdapter.KEY_USER);
      mTextColumn = cursor.getColumnIndexOrThrow(TwitterDbAdapter.KEY_TEXT);
      mProfileImageUrlColumn = cursor
          .getColumnIndexOrThrow(TwitterDbAdapter.KEY_PROFILE_IMAGE_URL);
      mCreatedAtColumn = cursor
          .getColumnIndexOrThrow(TwitterDbAdapter.KEY_CREATED_AT);
      mSourceColumn = cursor.getColumnIndexOrThrow(TwitterDbAdapter.KEY_SOURCE);

      mMetaBuilder = new StringBuilder();
    }

    private LayoutInflater mInflater;

    private int mUserTextColumn;
    private int mTextColumn;
    private int mProfileImageUrlColumn;
    private int mCreatedAtColumn;
    private int mSourceColumn;

    private StringBuilder mMetaBuilder;

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
      View view = mInflater.inflate(R.layout.tweet, parent, false);

      ViewHolder holder = new ViewHolder();
      holder.tweetUserText = (TextView) view.findViewById(R.id.tweet_user_text);
      holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
      holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
      holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text);
      view.setTag(holder);

      return view;
    }

    private static class ViewHolder {
      public TextView tweetUserText;
      public TextView tweetText;
      public ImageView profileImage;
      public TextView metaText;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
      ViewHolder holder = (ViewHolder) view.getTag();

      holder.tweetUserText.setText(cursor.getString(mUserTextColumn));
      Utils.setTweetText(holder.tweetText, cursor.getString(mTextColumn));

    //BEGIN: Added by Hanly De Los Santos
      String say = cursor.getString(mUserTextColumn)+&quot; said &quot;+cursor.getString(mTextColumn);

      while(!tweetStrings.contains(say))
    	  tweetStrings.add(say); 

    // END: Added by Hanly De Los Santos

      String profileImageUrl = cursor.getString(mProfileImageUrlColumn);

      if (!Utils.isEmpty(profileImageUrl)) {
        holder.profileImage.setImageBitmap(TwitterApplication.mImageManager.get(
            profileImageUrl));
      }

      try {
        Date createdAt = TwitterDbAdapter.DB_DATE_FORMATTER.parse(cursor
            .getString(mCreatedAtColumn));
        holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, createdAt,
            cursor.getString(mSourceColumn)));
      } catch (ParseException e) {
        Log.w(TAG, &quot;Invalid created at data.&quot;);
      }
    }

    public void refresh() {
      getCursor().requery();
    }

  }

  private void draw() {
    mTweetAdapter.refresh();
  }

  private void goTop() {
    mTweetList.setSelection(0);
  }

  private void enableEntry() {
    mTweetEdit.setEnabled(true);
    mSendButton.setEnabled(true);
  }

  private void disableEntry() {
    mTweetEdit.setEnabled(false);
    mSendButton.setEnabled(false);
  }

  // Actions.

  private void doSend() {
    if (mSendTask != null &amp;&amp; mSendTask.getStatus() == UserTask.Status.RUNNING) {
      Log.w(TAG, &quot;Already sending.&quot;);
    } else {
      String status = mTweetEdit.getText().toString();

      if (!Utils.isEmpty(status)) {
        mSendTask = new SendTask().execute();
      }
    }
  }

  private enum SendResult {
    OK, IO_ERROR, AUTH_ERROR, CANCELLED
  }

  private class SendTask extends UserTask&lt;Void, Void, SendResult&gt; {
    @Override
    public void onPreExecute() {
      onSendBegin();
    }

    @Override
    public SendResult doInBackground(Void... params) {
      try {
        String status = mTweetEdit.getText().toString();
        JSONObject jsonObject = getApi().update(status);
        Tweet tweet = Tweet.create(jsonObject);

        if (!Utils.isEmpty(tweet.profileImageUrl)) {
          // Fetch image to cache.
          try {
            getImageManager().put(tweet.profileImageUrl);
          } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
          }
        }

        getDb().createTweet(tweet, false);
      } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return SendResult.IO_ERROR;
      } catch (AuthException e) {
        Log.i(TAG, &quot;Invalid authorization.&quot;);
        return SendResult.AUTH_ERROR;
      } catch (JSONException e) {
        Log.w(TAG, &quot;Could not parse JSON after sending update.&quot;);
        return SendResult.IO_ERROR;
      } catch (ApiException e) {
        Log.e(TAG, e.getMessage(), e);
        return SendResult.IO_ERROR;
      }

      return SendResult.OK;
    }

    @Override
    public void onPostExecute(SendResult result) {
      if (isCancelled()) {
        // Canceled doesn't really mean &quot;canceled&quot; in this task.
        // We want the request to complete, but don't want to update the
        // activity (it's probably dead).
        return;
      }

      if (result == SendResult.AUTH_ERROR) {
        logout();
      } else if (result == SendResult.OK) {
        onSendSuccess();
      } else if (result == SendResult.IO_ERROR) {
        onSendFailure();
      }
    }
  }

  private void onSendBegin() {
    disableEntry();
    updateProgress(&quot;Updating status...&quot;);
  }

  private void onSendSuccess() {
    mTweetEdit.setText(&quot;&quot;);
    updateProgress(&quot;&quot;);
    enableEntry();
    draw();
    goTop();
  }

  private void onSendFailure() {
    updateProgress(&quot;Unable to update status&quot;);
    enableEntry();
  }

  private void doRetrieve() {
    Log.i(TAG, &quot;Attempting retrieve.&quot;);

    if (mRetrieveTask != null
        &amp;&amp; mRetrieveTask.getStatus() == UserTask.Status.RUNNING) {
      Log.w(TAG, &quot;Already retrieving.&quot;);
    } else {
      mRetrieveTask = new RetrieveTask().execute();
    }
  }

  private void onRetrieveBegin() {
    updateProgress(&quot;Refreshing...&quot;);
  }

  private enum RetrieveResult {
    OK, IO_ERROR, AUTH_ERROR, CANCELLED
  }

  private class RetrieveTask extends UserTask&lt;Void, Void, RetrieveResult&gt; {
    @Override
    public void onPreExecute() {
      onRetrieveBegin();
    }

    @Override
    public void onProgressUpdate(Void... progress) {
      draw();
    }

    @Override
    public RetrieveResult doInBackground(Void... params) {
      JSONArray jsonArray;

      long maxId = getDb().fetchMaxId();

      try {
        jsonArray = getApi().getTimelineSinceId(maxId);
      } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return RetrieveResult.IO_ERROR;
      } catch (AuthException e) {
        Log.i(TAG, &quot;Invalid authorization.&quot;);
        return RetrieveResult.AUTH_ERROR;
      } catch (ApiException e) {
        Log.e(TAG, e.getMessage(), e);
        return RetrieveResult.IO_ERROR;
      }

      ArrayList&lt;Tweet&gt; tweets = new ArrayList&lt;Tweet&gt;();
      HashSet&lt;String&gt; imageUrls = new HashSet&lt;String&gt;();

      for (int i = 0; i &lt; jsonArray.length(); ++i) {
        if (isCancelled()) {
          return RetrieveResult.CANCELLED;
        }

        Tweet tweet;

        try {
          JSONObject jsonObject = jsonArray.getJSONObject(i);
          tweet = Tweet.create(jsonObject);
          tweets.add(tweet);
        } catch (JSONException e) {
          Log.e(TAG, e.getMessage(), e);
          return RetrieveResult.IO_ERROR;
        }

        imageUrls.add(tweet.profileImageUrl);

        if (isCancelled()) {
          return RetrieveResult.CANCELLED;
        }
      }

      getDb().addTweets(tweets, false);

      if (isCancelled()) {
        return RetrieveResult.CANCELLED;
      }

      publishProgress();

      for (String imageUrl : imageUrls) {
        if (!Utils.isEmpty(imageUrl)) {
          // Fetch image to cache.
          try {
            getImageManager().put(imageUrl);
          } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
          }
        }

        if (isCancelled()) {
          return RetrieveResult.CANCELLED;
        }
      }

      return RetrieveResult.OK;
    }

    @Override
    public void onPostExecute(RetrieveResult result) {
      if (result == RetrieveResult.AUTH_ERROR) {
        logout();
      } else if (result == RetrieveResult.OK) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, Utils.getNowTime());
        editor.commit();
        draw();
        goTop();
      } else {
        // Do nothing.
      }

      updateProgress(&quot;&quot;);
    }
  }

  private class FollowersTask extends UserTask&lt;Void, Void, RetrieveResult&gt; {
    @Override
    public RetrieveResult doInBackground(Void... params) {
      try {
        ArrayList&lt;Long&gt; followers = getApi().getFollowersIds();
        getDb().syncFollowers(followers);
      } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return RetrieveResult.IO_ERROR;
      } catch (AuthException e) {
        Log.i(TAG, &quot;Invalid authorization.&quot;);
        return RetrieveResult.AUTH_ERROR;
      } catch (ApiException e) {
        Log.e(TAG, e.getMessage(), e);
        return RetrieveResult.IO_ERROR;
      }

      return RetrieveResult.OK;
    }

    @Override
    public void onPostExecute(RetrieveResult result) {
      if (result == RetrieveResult.OK) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, Utils
            .getNowTime());
        editor.commit();
      } else {
        // Do nothing.
      }
    }
  }

  // Menu.

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem item = menu.add(0, OPTIONS_MENU_ID_REFRESH, 0, R.string.refresh);
    item.setIcon(R.drawable.refresh);

    item = menu.add(0, OPTIONS_MENU_ID_DM, 0, R.string.dm);
    item.setIcon(android.R.drawable.ic_menu_send);

    /*
    item = menu.add(0, OPTIONS_MENU_ID_TOGGLE_REPLIES, 0,
        R.string.show_at_replies);
    item.setIcon(android.R.drawable.ic_menu_zoom);
    */

    return super.onCreateOptionsMenu(menu);
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    /*
    MenuItem item = menu.findItem(OPTIONS_MENU_ID_TOGGLE_REPLIES);

    if (isReplies()) {
      item.setIcon(R.drawable.ic_menu_zoom_out);
      item.setTitle(R.string.show_all);
    } else {
      item.setIcon(android.R.drawable.ic_menu_zoom);
      item.setTitle(R.string.show_at_replies);
    }
    */

    return super.onPrepareOptionsMenu(menu);
  }

  public void toggleShowReplies() {
    mState = mState == STATE_REPLIES ? STATE_ALL : STATE_REPLIES;

    SharedPreferences.Editor editor = mPreferences.edit();
    editor.putInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, mState);
    editor.commit();

    setupState();
  }

  private static final String INTENT_MODE = &quot;mode&quot;;
  private static final int MODE_REPLIES = 1;

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case OPTIONS_MENU_ID_REFRESH:
      doRetrieve();
      return true;
    case OPTIONS_MENU_ID_REPLIES:
      Intent repliesIntent = new Intent(this, TwitterActivity.class);
      repliesIntent.putExtra(INTENT_MODE, MODE_REPLIES);
      startActivity(repliesIntent);
      return true;
    case OPTIONS_MENU_ID_DM:
      launchActivity(DmActivity.createIntent());
      return true;
    case OPTIONS_MENU_ID_TOGGLE_REPLIES:
      toggleShowReplies();
      return true;
    }

    return super.onOptionsItemSelected(item);
  }

  // Various handlers.

  private View.OnKeyListener tweetEnterHandler = new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_ENTER
          || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
          doSend();
        }
        return true;
      }
      return false;
    }
  };

	@Override
	public void onInit(int arg0) {
		ttsReady = true;
	}
}
</pre>
<p>Below is the Speak class which simply takes in a string of text and utilizing the Text-to-Speech synthesizes it.</p>
<pre class="brush: plain;">
package com.dart.android.twitter;

import com.google.tts.TTS;

public class Speak {

	public void speak(boolean ttsReady, TTS myTTS, String textToSpeak){
		if (ttsReady) {
			// This param does only work on pre-recorded voice and has no
			// effect on this speak.
			String[] params = { &quot;VOICE_FEMALE&quot; };
			// Speaks the text
			myTTS.speak(textToSpeak, 1, params);
		} 

		else {
			// Notifys the user if the TTS service is not ready or installed
//			Toast.makeText(this, &quot;TTS is not ready or  installed&quot;,
//					Toast.LENGTH_LONG).show();
		}
	}

	public void stop(boolean ttsReady, TTS myTTS){
		myTTS.stop();
	}

}
</pre>
<p>If you want to try the working copy you can download it by clicking the link below.</p>
<p><a href="/school_content/bin/TwitterActivity.apk"><img src="/images/download_now.png"></a></p>

	Tags: <a href="http://www.hdelossantos.com/tag/android/" title="android" rel="tag">android</a>, <a href="http://www.hdelossantos.com/tag/code-assignment/" title="code assignment" rel="tag">code assignment</a>, <a href="http://www.hdelossantos.com/tag/device-programming/" title="device programming" rel="tag">device programming</a>, <a href="http://www.hdelossantos.com/tag/java/" title="java" rel="tag">java</a>, <a href="http://www.hdelossantos.com/tag/mobile-device/" title="mobile device" rel="tag">mobile device</a>, <a href="http://www.hdelossantos.com/tag/programming/" title="programming" rel="tag">programming</a>, <a href="http://www.hdelossantos.com/tag/speech-to-text/" title="speech-to-text" rel="tag">speech-to-text</a>, <a href="http://www.hdelossantos.com/tag/text-to-speech/" title="text-to-speech" rel="tag">text-to-speech</a>, <a href="http://www.hdelossantos.com/tag/text2speech/" title="text2speech" rel="tag">text2speech</a>, <a href="http://www.hdelossantos.com/tag/tts-library/" title="TTS library" rel="tag">TTS library</a>, <a href="http://www.hdelossantos.com/tag/tweet/" title="tweet" rel="tag">tweet</a>, <a href="http://www.hdelossantos.com/tag/tweets/" title="tweets" rel="tag">tweets</a>, <a href="http://www.hdelossantos.com/tag/twitta/" title="twitta" rel="tag">twitta</a>, <a href="http://www.hdelossantos.com/tag/twitter/" title="twitter" rel="tag">twitter</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/" title="Quick and easy Android HTTP POST of JSON string (December 24, 2009)">Quick and easy Android HTTP POST of JSON string</a> (4)</li>
	<li><a href="http://www.hdelossantos.com/2009/03/01/powers-of-base-2-in-mips/" title="Powers of base 2 in MIPS (March 1, 2009)">Powers of base 2 in MIPS</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/02/21/powers-of-base-2-in-c/" title="Powers of base 2 in C (February 21, 2009)">Powers of base 2 in C</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/03/15/powers-of-base-2-between-2-values-using-array-in-mips/" title="Powers of base 2 between 2 values using array in MIPS (March 15, 2009)">Powers of base 2 between 2 values using array in MIPS</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/" title="Using a SQLite Database in Android (January 7, 2010)">Using a SQLite Database in Android</a> (8)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/iEKndrgD4EEZgdfoV4ZgOKgwPLA/0/da"><img src="http://feedads.g.doubleclick.net/~a/iEKndrgD4EEZgdfoV4ZgOKgwPLA/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/iEKndrgD4EEZgdfoV4ZgOKgwPLA/1/da"><img src="http://feedads.g.doubleclick.net/~a/iEKndrgD4EEZgdfoV4ZgOKgwPLA/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/uHDS6zTdjB0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/10/10/talking-twitter/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/10/10/talking-twitter/</feedburner:origLink></item>
		<item>
		<title>Apparently I don’t know Spanish.</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/CPfGFLAGpFk/</link>
		<comments>http://www.hdelossantos.com/2009/09/27/apparently-i-dont-know-spanish/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 02:47:57 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=432</guid>
		<description><![CDATA[It seems that despite being born in a Spanish speaking country, having gone to school solely in Spanish for 3 years, having Spoken only Spanish at home my entire life (21 years), and having taken Spanish classes throughout elementary, high school, and a semester in college, still doesn&#8217;t qualify me as knowing Spanish according to [...]]]></description>
			<content:encoded><![CDATA[<p>It seems that despite being born in a Spanish speaking country, having gone to school solely in Spanish for 3 years, having Spoken only Spanish at home my entire life (21 years), and having taken Spanish classes throughout elementary, high school, and a semester in college, still doesn&#8217;t qualify me as knowing Spanish according to Tyler. </p>
<p>In his deeply distorted mind he believes that the verb &#8220;gustar&#8221; means to please. While I will admit that depending on the context it does mean that, he would apply that meaning to the translation of:<br />
&#8220;A Hanly le gusta la muchacha.&#8221; thus making it &#8220;The girl pleases Hanly.&#8221; This translation completely redefines the meaning of the sentence giving it a sexual undertone and changing the structure from Hanly liking the girl (the correct meaning) to the girl pleasing Hanly (Tyler&#8217;s translation). Even applying it to the mother tongue of all romance languages Tyler&#8217;s translation would not make sense. For example this sentence in Latin would be &#8220;Hanly amat puellam.&#8221; Which would of course be translated into English as &#8220;Hanly likes(or loves) the girl.&#8221; The subject of the sentence being Hanly and the girl taking the singular accusative ending of -am because she is the direct object of Hanly&#8217;s love or liking. I&#8217;m sure he would argue that this is Latin and not Spanish, but the &#8220;A&#8221; in the beginning of the Spanish sentence preceding Hanly clearly makes Hanly the subject of the sentence stating that Hanly is the one doing the liking and not the girl. The girl of course being the direct object of Hanly&#8217;s liking.</p>
<p>My translation is of course wrong since I am completely inept and unable to speak my own country&#8217;s language. Does this mean that I communicate with my family through a telepathic link? Tyler of course, with his much higher standards, 4 years (a generous assumption considering he might have taken fewer years of it) of Spanish classes, and an inability to properly enunciate Spanish words, knows more Spanish than I could ever hope to learn. Debido a esto estoy avergonzado de haber nacido en Cuba y no saber hablar mi propio idioma. En verdad es un gran insulto no solamente a mi, pero a mi familia que venga este chiquito a decirme que yo no se hablar mi propio idioma. Que se valla para casa del carajo y me deje tranquilo este chiquito que se tira los peos mas altos que culo. </p>
<p>&#8212;Disculpenme por mi vulgaridad en esta explosión de mi temperamento sarcástico cubano.</p>
No tags for this post.
	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li>No related posts.</li>
	</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/ufBeF5-n2DQOXEDCbJlwFhVOMtg/0/da"><img src="http://feedads.g.doubleclick.net/~a/ufBeF5-n2DQOXEDCbJlwFhVOMtg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ufBeF5-n2DQOXEDCbJlwFhVOMtg/1/da"><img src="http://feedads.g.doubleclick.net/~a/ufBeF5-n2DQOXEDCbJlwFhVOMtg/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/CPfGFLAGpFk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/09/27/apparently-i-dont-know-spanish/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/09/27/apparently-i-dont-know-spanish/</feedburner:origLink></item>
		<item>
		<title>My thoughts on the state of government</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/9ZKzgjh-V_M/</link>
		<comments>http://www.hdelossantos.com/2009/08/22/my-thoughts-on-the-state-of-government/#comments</comments>
		<pubDate>Sat, 22 Aug 2009 06:11:48 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Politics]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=415</guid>
		<description><![CDATA[A friend of mine sent me this video:

and it got me thinking about the reasons why my family came to the United States. Those that know me know that I was born in Cuba, which has had a communist regime in place for 50 years. Like many Cuban children who have never been exposed to [...]]]></description>
			<content:encoded><![CDATA[<p>A friend of mine sent me this video:</p>
<div align="center"><object id="VideoPlayback" style="width: 400px; height: 326px;" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="100" height="100" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://video.google.com/googleplayer.swf?docid=6732659166933078950&amp;hl=en&amp;fs=true" /><param name="allowfullscreen" value="true" /><embed id="VideoPlayback" style="width: 400px; height: 326px;" type="application/x-shockwave-flash" width="100" height="100" src="http://video.google.com/googleplayer.swf?docid=6732659166933078950&amp;hl=en&amp;fs=true" allowfullscreen="true"></embed></object></div>
<p>and it got me thinking about the reasons why my family came to the United States. <span id="more-415"></span>Those that know me know that I was born in Cuba, which has had a communist regime in place for 50 years. Like many Cuban children who have never been exposed to other forms of government and have been taught to despise American imperialism, I didn&#8217;t think much of the situation. That is, until we moved to the United States in 1995. In Cuba one lives under many restrictions imposed by the government: one is not allowed to kill cows (which inherently means one is not allowed to eat beef&#8230;the cattle is the property of the government), people are allotted certain amounts of food (when you turn 7 you are no longer allotted milk), the <em>meat</em> you are allotted is soy based. Living under these conditions, many people choose to turn to the black market to obtain food. My dad often tells the story of people who would kill cows in the middle of the night and cover themselves with a black tarp while butchering the cow. Within an hour, the cow would be butchered and the meat sold. Like the video says, the Cuban people gave up their freedoms and entrusted them to a revolutionary leader who incited anarchy against the established government. Anarchy was the transient state to the communist oligarchy which exists today.</p>
<p>Having experienced another form of government completely different of that in the United States, I understand what the forefathers set out to create in order to protect the rights of the people. I consider myself to be a Libertarian. When it comes to the United States, I believe that government should rule by the constitution and uphold the laws which our forefathers set in place in the creation of our republic. In essence I believe in laissez-faire, where government should only step in to protect the rights of the people by guiding businesses and other institutions in the right direction. Recently it seems that the United States has started trekking down the path to fascism, where the government has set rules in place for businesses to operate under. The government is essentially the majority shareholder in the car industry and possibly the financial industry as well. The government has influenced banks to buy other failing banks. The government has also limited the freedoms of the people, and has set in place the means to monitor citizens&#8217; communications without the need for warrants. It has forced telecommunications companies to create backdoors, and when charges are brought up against them has pardoned them. The government has soiled the constitutions, and the majority of Americans have accepted it without even a peep. They believe that the government has a right to do these things. The truth is that we, the people are the government. We are the ones which gave up or freedoms in the <a href="http://en.wikipedia.org/wiki/State_of_nature">state of nature</a> to form our government to protect our freedoms, not to monitor and control us. We the people have a right to debate, we elect our representatives into congress, we elect our president, we elect our government with the hope that it will represent us justly.</p>
<p>In the post 9/11 fear, we allowed the tables to turn. We allowed our government to control us. We allowed our government to attack a nation which we were told had <em>Weapons of Mass Destruction</em> (which turned out to be a lie our government told us). What have we done about it&#8230;nothing. Charges have been brought up against the previous administration, but nothing has happened. We (I voted independent) elected a president which promised us <em>change</em>, and what has he done? Given more money to the rich corporations so that they can shower themselves with lavish bonuses. He has maintained the unconstitutional watch on the people. Organizations such as <a href="http://www.flickr.com">flickr</a> censor <a href="http://www.sfgate.com/cgi-bin/blogs/scavenger/detail?entry_id=41498">anti-Obama commentary</a> off of their servers.</p>
<p>Us Americans are headed down the wrong path. We have come to appreciate and depend on government handouts (welfare, social security, medicare, and soon to be health care). The more of these social systems we set in place and the more we let the government run things, the closer we get to socialism. We have lost our pride in our country and have left a pack of weasels to run it, and it shows in the legislation that has left Washington these past 9 years.</p>
<p>We must remember why it is that we came to the new world, why we established the form of government we have. We must elect representatives not on the basis of what they can get us, but of how they will protect our freedoms. The government was established to protect our freedoms, not to give us handouts. We must earn our money through work, innovation, and competition. That is the American way which we have forgotten. Many Americans have been adapted to the notion of a bipartisan system and feel compelled to either vote Republican or Democrat, if we want real change, we should stand together and boycott the monopoly these two parties have created. We must stand together and vote for a representative of a 3rd party. We must take back our country!</p>
No tags for this post.
	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li>No related posts.</li>
	</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/b_EyGB0V6UefJxh_Q5zz-dxjlSo/0/da"><img src="http://feedads.g.doubleclick.net/~a/b_EyGB0V6UefJxh_Q5zz-dxjlSo/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/b_EyGB0V6UefJxh_Q5zz-dxjlSo/1/da"><img src="http://feedads.g.doubleclick.net/~a/b_EyGB0V6UefJxh_Q5zz-dxjlSo/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/9ZKzgjh-V_M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/08/22/my-thoughts-on-the-state-of-government/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/08/22/my-thoughts-on-the-state-of-government/</feedburner:origLink></item>
		<item>
		<title>Sunset After a Storm</title>
		<link>http://feedproxy.google.com/~r/hdelossantos/~3/r_TveF_wbnE/</link>
		<comments>http://www.hdelossantos.com/2009/06/25/407/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 05:24:07 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Photography]]></category>
		<category><![CDATA[art]]></category>
		<category><![CDATA[cuba]]></category>
		<category><![CDATA[photograph]]></category>
		<category><![CDATA[pictures]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=407</guid>
		<description><![CDATA[An oldie but I do have to admit it is one of my favorite pictures I have ever taken. I love the colors as the sun sets behind the clouds. I took this on my trip to Cuba in 2005.

	Tags: art, cuba, photograph, pictures

	Related posts
	
	A Very Eventful Yesterday (0)
	What&#8217;s with all the vampires? (0)
	Things to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.hdelossantos.com/blog/wp-content/uploads/2009/06/IMG_0618-1024x768.jpg" class="lightview" rel="gallery[407]" class="lightview" title="Sunset After a Storm"><img class="aligncenter size-medium wp-image-406" title="Sunset After a Storm" src="http://www.hdelossantos.com/blog/wp-content/uploads/2009/06/IMG_0618-300x225.jpg" alt="Sunset After a Storm" width="300" height="225" /></a>An oldie but I do have to admit it is one of my favorite pictures I have ever taken. I love the colors as the sun sets behind the clouds. I took this on my trip to Cuba in 2005.</p>

	Tags: <a href="http://www.hdelossantos.com/tag/art/" title="art" rel="tag">art</a>, <a href="http://www.hdelossantos.com/tag/cuba/" title="cuba" rel="tag">cuba</a>, <a href="http://www.hdelossantos.com/tag/photograph/" title="photograph" rel="tag">photograph</a>, <a href="http://www.hdelossantos.com/tag/pictures/" title="pictures" rel="tag">pictures</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.hdelossantos.com/2009/05/03/a-very-eventful-yesterday/" title="A Very Eventful Yesterday (May 3, 2009)">A Very Eventful Yesterday</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/06/22/whats-with-all-the-vampires/" title="What&#8217;s with all the vampires? (June 22, 2009)">What&#8217;s with all the vampires?</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/05/10/things-to-do-back-home/" title="Things to do Back Home (May 10, 2009)">Things to do Back Home</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2008/12/09/sledding-down-liz-hill/" title="Sledding down Liz Hill. (December 9, 2008)">Sledding down Liz Hill.</a> (0)</li>
	<li><a href="http://www.hdelossantos.com/2009/03/16/my-vacuum-chamber-terrarium/" title="My Vacuum Chamber Terrarium (March 16, 2009)">My Vacuum Chamber Terrarium</a> (0)</li>
</ul>


<p><a href="http://feedads.g.doubleclick.net/~a/bi1YGnIrN9w0RoLpR6NBCeBmMCU/0/da"><img src="http://feedads.g.doubleclick.net/~a/bi1YGnIrN9w0RoLpR6NBCeBmMCU/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/bi1YGnIrN9w0RoLpR6NBCeBmMCU/1/da"><img src="http://feedads.g.doubleclick.net/~a/bi1YGnIrN9w0RoLpR6NBCeBmMCU/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/hdelossantos/~4/r_TveF_wbnE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/06/25/407/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.hdelossantos.com/2009/06/25/407/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 1.574 seconds --><!-- Cached page served by WP-Cache -->
