Android Basics – Learn about the changeCursor method to refresh Cursor data

You have seen how to use a Cursor to fetch data from a SQLite database. And then how to use a CursorAdapter to display the data in a ListView.

One problem with a Cursor is that it does not track the database changes. So if the data gets updated a cursor won’t present the updated version until the Activity gets recreated.

To illustrate this I have added a ListView in the layout xml, to display the surveys which have been added to the database.

To overcome this problem in the Activity onRestart method you need to use the changeCursor method. Refer to the below code segment.
Layout XML Code

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/displaySurveyDataId"/>

MainActivity Code

@Override
public void onRestart(){
    super.onRestart();

    Log.v(TAG, "Check for data refresh");

    try {
        SurveyDBHelper surveyDBHelper = new SurveyDBHelper(this);
        SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

        Cursor cursor = surveyDBHelper.getSurveyData(db);

        ListView lv = (ListView) findViewById(R.id.displaySurveyDataId);

        CursorAdapter ca = (CursorAdapter)lv.getAdapter();
        ca.changeCursor(cursor);

    }catch (SQLiteException e){
        Log.v(TAG, "Exception "+e.getMessage());
    }
}

Please follow the video to understand this better. Also the source code is available here for reference.

Android Basics – Learn how to use a CursorAdapter to bind data from a Cursor to a ListView

Suppose you are using a ListView to display a list of items. And these items come from the database. To help you implement this functionality CursorAdapter comes in handy.

It is like a ListAdapter. The difference being that instead of getting data from an Array it gets from the database.

Another advantage of using CursorAdapter is that the number of items it fetches from the database is equal to the number which can be displayed on screen.

So for instance if the table has 100 rows and the app can display only 5 at a time, then CursorAdapter will get only 5 rows.

As the user scrolls it pulls more data. This makes a CursorAdapter efficient.

You will use a SimpleCursorAdapter which implements a CursorAdapter in your App. Let’s see how.

The Constructor which you will be using will look like:

public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to, int flags)

The parameter details are available in Android documentation.

“flags” will be set to 0 for demonstration purpose.

If you are using a CursorAdapter then you do not need to close the cursor and the database. You can do this in the onDestroy lifecycle method.

Source Code is available here

Android Basics – Learn how to Navigate a Cursor to get data

In an earlier Article you saw how to populate data, from the database, to a cursor using the query() method.

Once the Cursor has data you can iterate over it. On every iteration you can get data corresponding to a row in the table.

There are four main methods available to navigate through a Cursor:

  • moveToFirst()
  • moveToLast()
  • moveToPrevious()
  • moveToNext()

In the example below we demonstrate how to use moveToFirst() method

//Sample Code to query the database
try {
    SurveyDBHelper surveyDBHelper = new SurveyDBHelper(this);
    SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

    Cursor cursor = surveyDBHelper.getSurveyData(db);

    if (cursor.moveToFirst()) {
        //Get the data
        String name = cursor.getString(1);
        String email = cursor.getString(2);
        Log.v(TAG, "Name "+name);
    }

    cursor.close();
    db.close();
}catch (SQLiteException e){
    Log.v(TAG, "Exception "+e.getMessage());
}
//End

Source code is available here for reference.

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