android10

  • Increase font size
  • Default font size
  • Decrease font size

Using the SQLite Database with ListView

E-mail Print
( 2 Votes )
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.

sqlite_crash_course_01


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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class DatabaseHelper extends SQLiteOpenHelper {
 
public DatabaseHelper(Context context) {
super(context, "CursorDemo", null, 1);
}
 
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS names ("
+ BaseColumns._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, first VARCHAR, last VARCHAR)");
db.execSQL("INSERT INTO names (first, last) VALUES ('John', 'Doe')");
db.execSQL("INSERT INTO names (first, last) VALUES ('James', 'Kirk')");
}
 
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Steps to upgrade the database for the new version ...
}
}

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:
  1. 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.
  2. getReadableDatabase and getWritableDatabase will provide a SQLiteDatabase, similar to the one that was used to create or update the database.
  3. Use one of SQLiteDatabase‘s query methods to obtain a Cursor, which provides access to the result set.
  4. Create a CursorAdapter based on the Cursor.
  5. Set the ListView to use the created CursorAdapter.
The CursorAdapter is an abstract class, requiring the bind and newView to be defined. This allows you to control the view that is used to display the data for an entry in the view. However, in many cases, the SimpleCursorAdapter would be sufficient. This fragment uses the above DatabaseHelper class to provide data for a ListView in a ListActivity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class SQLiteDemo extends ListActivity {
private static final int DIALOG_ID = 100;
 
private SQLiteDatabase database;
 
private CursorAdapter dataSource;
 
private View entryView;
 
private EditText firstNameEditor;
 
private EditText lastNameEditor;
 
private static final String fields[] = { "first", "last",
BaseColumns._ID };
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("names", fields,
null, null, null, null, null);
 
dataSource = new SimpleCursorAdapter(this,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
 
...
 
setListAdapter(dataSource);
}
 
...
}
 

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
2
3
4
5
6
7
8
ContentValues values = new ContentValues();
values.put("first", firstNameEditor.getText()
.toString());
values.put("last",
lastNameEditor.getText().toString());
database.insert("names", null, values);
dataSource.getCursor().requery();
 

You can find the full source code for this example below.
Thanks kahdev for this amazing article!!!

Source code files
FileDescriptionSDK VersionFile sizeLast Modified
Download this file (SQLiteWithListView.zip)SQLiteWithListView.zipThe source code for this example413 Kb05/11/10 15:58
Comments (6)
  • allnighter453

    force closes when i try to run it....i have all the res and all your classes...

  • kitti_chim

    Thank you

  • spraveen
    avatar

    Force Close will show when i try to run.

  • laxman  - Android

    Could u PLZ any one tell me , How can save my data in Android Mobiles using SQLite with source code

  • jyoti299  - error

    i download the SQLiteWithListView.zip and run it but it shows error . so what will i do
    plz help me

Only registered users can write comments!
 

ANDROID10 --- TIP!!!

android10 tipIf you are writing an article and want to include your source code or a file...is pretty simple: first you save your article for first time to create it, then you edit it and at bottom of the editor, you have a button "Add Attachment"...just click it, upload your file...and that's all...too easy...
contact android10!!!