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.

Author: androidsmartly

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

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