<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Hdelossantos.com&#187; Tutorials</title>
	<atom:link href="http://www.hdelossantos.com/category/technology/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hdelossantos.com</link>
	<description>Tales of the Wisconsin Experience</description>
	<lastBuildDate>Wed, 18 Aug 2010 02:04:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Using a SQLite Database in Android</title>
		<link>http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/</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[Blog]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database adapter]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[step-by-step]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[tv]]></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 [...]]]></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 class="lightview" href="http://www.hdelossantos.com/blog/wp-content/uploads/2010/01/DBAdaptrTest.png"><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>
]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2010/01/07/using-a-sqlite-database-in-android/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Quick and easy Android HTTP POST of JSON string</title>
		<link>http://www.hdelossantos.com/2009/12/24/quick-and-easy-android-http-post-of-json-string/</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[Blog]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[google]]></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[show]]></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>
]]></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>
		</item>
		<item>
		<title>Creating a SQLite database in Android</title>
		<link>http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/</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[Blog]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android project]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[art]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database adapter]]></category>
		<category><![CDATA[database table]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[show]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[step-by-step]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[tv]]></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. [...]]]></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: #B20000;">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>
]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2009/12/23/creating-a-sqlite-database-in-android/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.642 seconds -->
