KIO
Kreative Ideen online
changeCursor()

changeCursor()

Cursors don’t automatically keep trac of whether the underlying data in the dabase has changed. So if the underlying data chages after the cursor’s been created, the cursor doesn’t get updated: it still contans the original records, and none of the chages.

Excample:

If you have an activity that displays data (a list with favorites) and you call a other activity and changes (add’s or removes a favorite-item), when use the backbutton to the first activity the listview will not include the new drink.

Cursors don’t automatically refresh

This is because cursors retrieve data when the cursor gets created.
Example:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_level);
         ListView listFavorites = (ListView)findViewById(R.id.list_favorites);

        try {
            SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
            db = starbuzzDatabaseHelper.getReadableDatabase();
            favoritesCursor = db.query("DRINK",new String[]{"_id","NAME"},"FAVORITE = 1", null,null,null,null);
            CursorAdapter favoriteAdapter = new SimpleCursorAdapter(TopLevelActivity.this,android.R.layout.simple_list_item_1,favoritesCursor,new String[]{"NAME"},new int[]{android.R.id.text1},0);
            //Set the curser adapter to the list view
            listFavorites.setAdapter(favoriteAdapter);
        } catch (SQLiteException e) {
            Toast toast = Toast.makeText(this,"Database unavailable",Toast.LENGTH_SHORT);
            toast.show();
        }
   }

So it gets its data when the activity is created. When you navigate through the other activities, TopLevelAvtivity is stopped. It’s not destroyed and recreated, so neiither is the cursor.

Solution: change cursor in onRestart()

  • Define the cursor
  • Get a reference to the cursor adapter
  • Change the cursor using chageCursor()
    @Override
    public void onRestart(){
        super.onRestart();
        Cursor newCursor = db.query("DRINK",new String[]{"_id","NAME"},"FAVORITE = 1",null,null,null,null);
        ListView listFavorites = (ListView)findViewById(R.id.list_favorites);
        CursorAdapter adapter = (CursorAdapter)listFavorites.getAdapter();
        //Switch the cursor being used by the list_favorites list view to the new cursor
        adapter.changeCursor(newCursor);
        /*Change the value of favoritesCursor to the new cursor so
        we can change it in the activity's onDestroy() method
         */
        favoritesCursor = newCursor;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *