Search code examples
androiddatabaselistviewlistactivityandroid-cursoradapter

How to save a ListView to database in one go


I am new to Android programming and have a basic question.

I have created a ListActivity where each row in its ListView has a TextView and a RatingBar. I am able to display values in the TextView and RatingBar by reading them from a pre-populated database; I am doing this via a custom CursorAdapter and it's bindView() method, i.e.

public class MyCursorAdapter extends CursorAdapter {
    ...

    public void bindView(View view, Context context, final Cursor cursor) {
        TextView name = (TextView)view.findViewById(R.id.name);
        name.setText(cursor.getString(cursor.getColumnIndex(MyDbAdapter.KEY_NAME)));
        RatingBar rating = (RatingBar)view.findViewById(R.id.life_bar_rating);
        rating.setRating(cursor.getFloat(cursor.getColumnIndex(MyDbAdapter.KEY_RATING_VALUE)));
    }

    ...
}

Now, my problem is that in my ListActivity I want the user to be able to click a "Save" button so that all changes are saved to the database in one go?. How would I iterate through the adapter to get the row ID and rating values so they can be saved (or is there another better way of doing this?).

The reason why I want to do a save in one go is because I thought it would be bad practice to update the database every time the user makes a change to a single rating (even though this is easier) as this causes more wear and tear on flash memory. I may be wrong about this, but I thought that there are a limited number of reads and writes with flash memory.


Solution

  • Remember the Adapter's backing array? The one you used to initialize it? save that ;)

    or if that doesn't work...

    for(int i = 0; i < listView.getAdapter().getCount(); i++)
        SaveThing(listView.getAdapter().getItem(i));
    

    if you need SQLite examples of saving... tomorrow.

    edit for same of keeping comments clean:

    as far as that object thing goes - you're free to cast it to anything that's in the listview. the data type, not view type.

    so for example, an arrayAdapter that works with strings still returns Objects. but you will most certainly cast them to Strings because you know that's what you put in. it's awkward but thats how it is.