Search code examples
androiddatabaselistviewandroid-cursoradapterratingbar

How to iterate through Android ListView to get RatingBar values?


I have created a custom CursorAdapter which binds some view items (a TextView and a RatingBar) in a ListView to some columns in a SQL database via bindView(), 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)));
    }

    ...
}

I want to get the absolute latest version of all of the RatingBar rating values so I can update the database accordingly (in one go). I was initially trying to use the cursor in my CursorAdapter, however I noticed that the cursor just contains the values stored in the database and not the latest user changes - is this expected (the documentation is a bit vague)?.

I am guessing I need to iterate through the actual views somehow - how would I iterate through my ListView to retrieve all of the new rating bar rating values?


Solution

  • You can also make your Cursor final in onBindView(), create field HashMap<id, rating> mRatings; in your CursorAdapter

    public class MyCursorAdapter extends CursorAdapter implements RatingBar.OnRatingBarChangeListener {
    
        public void bindView(View view, Context context, final Cursor cursor) {
            ...
            rating.setTag(cursor.getPosition());
            rating.setOnRatingBarChangeListener(this);
            ...
        }
    
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromTouch) {
            Integer position = (Integer) ratingBar.getTag();
            Cursor c = getCursor();
            c.move(position);
            int id = cursor.get id;
            mRatings.add(id, rating);
        }
    

    And later you traverse mRatings and update changed ratings in one transaction.