Android Basics – Learn how to use Cursor to get data from SQLite

In the last lecture you learnt how to upgrade and downgrade your database.

Now that you have a database and a table in place let’s try to understand how to query the database to get data.

Cursor gives you access to the database. In order to use a Cursor you need to use a Query.

To read from a database, use the query() method, passing it your selection criteria and desired columns.

Here is how the query method looks like

query(String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)

Here is a simple example from the Survey app code base

 

public Cursor getSurveyData(SQLiteDatabase db){

    // Define a projection that specifies which columns from the database you will actually use after this query.

    String[] projection = {
            "_id",
            SURVEY_TABLE_NAME_COLUMN,
            SURVEY_TABLE_EMAIL_COLUMN,
            SURVEY_TABLE_AGE_COLUMN
    };

    // How you want the results sorted in the resulting Cursor
    String sortOrder = "_id" + " DESC";

    return db.query(
            SURVEY_TABLE,
            projection,
            null, null, null, null,
            sortOrder
    );
}

 

Please follow the video and refer to the source code.

References