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

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

2 thoughts on “Android Basics – Learn how to use Cursor to get data from SQLite”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s