Share
Introduction
The dev guide provides information on how to set up a database for your application. This essentially involves extending SQLiteOpenHelper and overriding its onCreate and onUpgrade methods. Both methods are given a SQLiteDatabase object, which you use to execute the SQL queries to setup the database.
Using the SQLite DB with ListView
In the following example, the a table called names is created with three columns – an id column and first and last columns for storing the first and last names, respectively, and inserts a couple of initial entries.
1 |
public class DatabaseHelper extends SQLiteOpenHelper { |
A note on the dev guide recommends having an id column that has the same name as the BaseColumns._ID constant. The onUpgrade needs to be implemented only in subsequent versions, where the structure of the database has changed. It should perform only the necessary operations to upgrade the database (e.g. create only the new tables, drop ones that are no longer needed, alter tables old tables to match the new one, etc.).
Then, to populate a ListView with data from the database:
- Create the instance of your SQLiteOpenHelper and open the database with either getReadableDatabase or getWritableDatabase. You must use getWritableDatabase if you intend to add data to the database.
- getReadableDatabase and getWritableDatabase will provide a SQLiteDatabase, similar to the one that was used to create or update the database.
- Use one of SQLiteDatabase‘s query methods to obtain a Cursor, which provides access to the result set.
- Create a CursorAdapter based on the Cursor.
- Set the ListView to use the created CursorAdapter.
1 |
public class SQLiteDemo extends ListActivity { |
In some cases, the some data will be added, deleted or changed while the view is still displaying. The view will need to be updated to reflect these changes. In Android, you only have to call the Cursor‘s requery method. This will also update the view. The following snippet follows from the above examples. It creates an entry, based on the contents of a couple of EditText fields and updates the view, simply by calling requery.
1 |
ContentValues values = new ContentValues(); |
You can find the full source code for this example below.
Thanks kahdev for this amazing article!!!
Comments (6)
-
2010-11-23 08:53:10 |Author| suresh.vempower
-
2011-06-14 19:16:19 |Author| allnighter453
force closes when i try to run it....i have all the res and all your classes...
-
2011-06-20 05:50:05 |Author| kitti_chim
Thank you
-
2011-07-22 09:00:41 |Author| spraveen
Only registered users can write comments!







thank u very much