简体   繁体   中英

Android SimpleCursorAdapter and Database Update

I just started with Android development and love it so far. To get some experience, I am writing a little todo application. In my database I have a state for a todo item, represented as int. I use a checkbox in a list view to represent this state. To bind the data to the view, I use a subclass of SimpleCursorAdapter. I add an onClickListener to the checkbox that updates the state in the database for the used list item. The problem is, if I use the following code, the list is screwed up in the display (many items will be checked):

@Override
public View getView(final int pos, View inView, ViewGroup parent) {
  View view = inView;
  if (view == null) {
    LayoutInflater inflater = (LayoutInflater) context
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.toodoolist_item, null);
  }
  cursor.moveToPosition(pos);
  ...

  checkBox.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
        int state = 0;
        if (checkBox.isChecked()) {
        titleView.setPaintFlags(titleView.getPaintFlags()
            | Paint.STRIKE_THRU_TEXT_FLAG);
        titleView.setEnabled(false);
        state = 1;
     } else {
        titleView.setPaintFlags(titleView.getPaintFlags()
            ^ Paint.STRIKE_THRU_TEXT_FLAG);
        titleView.setEnabled(true);
     }

     ContentValues values = new ContentValues();
     values.put(TooDooTable.STATE, state); 
     context.getContentResolver()
        .update(ContentUris.withAppendedId(
     TooDooTable.CONTENT_URI, id), values, null, null);
     cursor.requery();
  }
}

My current workaround is to use the inflater every time, even if the inView is not null:

 @Override
 public View getView(final int pos, View inView, ViewGroup parent) {
   View view = inView;
   LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   view = inflater.inflate(R.layout.toodoolist_item, null);
  ...

This works, but I don't understand why I have to do this hack.

What would be the best practice to update the database in a CurserAdapter and get the changes reflected immediately in the view?

Thanks

Kai

使用notifyDataSetChanged而不是重新查询,并且如果以前的方法没有执行任何操作,则可以在视图上使用invalidate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM