Getting started with android-sqlite

Download android-sqlite eBook

Remarks

The SQLite library itself has only a C API; to make it accessible from Java, the Android framework wraps this with the android.database.sqlite package. The most important classes are SQLiteDatabase and SQLiteOpenHelper.

The android.database package contains the database-related parts of the framework that are not SQLite specific.

Versions

API Level

API LevelPlatform VersionNameRelease Date
11.0Base2008-09-23
52.0Eclair2009-10-26
82.2Froyo2010-05-20
113.0Honeycomb2011-02-22
164.1Jelly Bean2012-07-09
194.4Kitkat2013-10-31
236.0Marshmallow2015-10-05

Basic usage

To include a database in your app, you typically derive a class from SQLiteOpenHelper:

public class HelloDBHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final int DATABASE_NAME = "hello";

    HelloDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE ...");
        ...
    }
}
 

This helper class is responsible for opening (and creating/updating, if needed) the database. Use it to get an SQLiteDatabase object to access the data:

SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query(...);
while (c.moveToNext()) {
    String name = c.getString(0);
    ...
}
 
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("column", value);
...
db.insertOrThrow("table", null, cv);
 

Stats

41 Contributors: 2
Friday, August 5, 2016
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook