[小坑]调用CursorAdapter中的notifyDataSetChanged后,对应绑定的ListView没有自动刷新

最近在调试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);
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值