Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using an SQLite Database in an Android Application

Author: Rachee Singh
Published? true
FormatLanguage: WikiFormat

Problem:

Data persistence in the application.

Solution:

Using SQLite to store the application data. This would involve inherit SQLiteOpenHelper class.

Discussion:

In order to use SQLite databases in an Android application, it is necessary to inherit SQLiteOpenHelper class. This is an inbuilt class that helps load a database file. It checks for the existence of the database file and if it exists, it loads it otherwise it creates one.

public class SqlOpenHelper extends SQLiteOpenHelper {

The constructor for the SQLiteOpenHelper class takes in a few arguments: Context, database name, CursorFactory object (may be null), database schema version number. The schema version is used to decide when to run your onUpdate() method.

        public static final String DBNAME = "tasksdb.sqlite";
	public static final int VERSION =1;
	public static final String TABLE_NAME = "tasks";
	public static final String ID= "id";
	public static final String NAME="name";
	
	public SqlOpenHelper(Context context) {
		super(context, DBNAME, null, VERSION);
		
}

Creating a database in SQL uses the "create" statement:

create table <table-name> (column1 integer PRIMARY key AUTOINCREMENT not null, column2 TEXT);

	public void onCreate(SQLiteDatabase db) {
		createDatabase(db);
	}

	private void createDatabase(SQLiteDatabase db) {
		db.execSQL("create table " + TABLE_NAME + "(" +
			ID + " integer primary key autoincrement not null, " + 
			NAME + " text " 
			+ ");"
			);
	}

To get a handle on the SQL database you created, instantiate the class inheriting SQLiteOpenHelper:

	SqlOpenHelper helper = new SqlOpenHelper(this);
	SQLiteDatabase database= helper.getWritableDatabase();

Now, the SQLiteDatabase database can be used to load elements stored in the database, update and insert elements to it.

No records found.