最近在调试contentprovider时想要将查询得到的cursor同activity中的ListView关联起来,实现contentprovider内容变化时自动触发也面更新,网上随便查了个方法,具体为:
在ContentResolver上注册个observer,这样对应的contentprovider内容发生变化时,会调用observer的onChange方法,onChange中调用CursorAdaptor的notifyDataSetChanged来实现自动刷新ListView
调试中发现我的app在observer回调后并未将contentprovider变化的内容自动更新到ListView中,经排查发现,是CursorAdaptor的构造器第二个参数导致的:
private class MyAdapter extends CursorAdapter {
private Context context;
private Cursor cursor;
public MyAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
this.context = context;
this.cursor = c;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.list_item, null);
if (null != cursor) {
view.setTag(cursor.getInt(cursor.getColumnIndex("_id")));
}
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView main_title = (TextView) view.findViewById(R.id.main_title);
TextView vice_title = (TextView) view.findViewById(R.id.vice_title);
if (null != cursor) {
main_title.setText(cursor.getString(cursor.getColumnIndex("name")));
vice_title.setText(cursor.getString(cursor.getColumnIndex("number")));
}
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
}
在MyAdapter 创建时,将第二个参数,自动查询置成了false,导致不能通过notifyDataSetChanged方法自动刷新
顺便看一下CursorAdapter源码,其中默认自动刷新的构造器已经被Deprecated掉了啊......原因可参见注释
/**
* Constructor that always enables auto-requery.
*
* @deprecated This option is discouraged, as it results in Cursor queries
* being performed on the application's UI thread and thus can cause poor
* responsiveness or even Application Not Responding errors. As an alternative,
* use {@link android.app.LoaderManager} with a {@link android.content.CursorLoader}.
*
* @param c The cursor from which to get the data.
* @param context The context
*/
@Deprecated
public CursorAdapter(Context context, Cursor c) {
init(context, c, FLAG_AUTO_REQUERY);
}