2011-06-16 48 views
1

我有一个活动在Sqlite数据库上运行查询,获取游标,使用该游标创建CustomCursorAdapter,并将其附加到活动中的ListView。它看起来像这样:避免使用游标的ANR

SQLiteDatabase db=new StuffHelper(this).getWritableDatabase(); 
Cursor c1=db.query(StuffHelper.TABLE, 
      new String[]{StuffHelper._ID}, 
      StuffHelper.SIZE+">=?", 
      new String[]{"64"}, 
      null, 
      null, 
      null); 
startManagingCursor(c1); 

StuffAdapter a1 = new StuffAdapter(this, c1); 

ListView ll1 = (ListView) findViewById(R.id.ll1); 
ll1.setAdapter(a1); 

这是目前的设置ANR方面的问题吗?当使用游标时,我如何告诉android在后台线程上运行所有Sqlite的东西?

回答

1

你没有给当这段代码运行的多语境,但无论如何,我会咬...

是的,它运行的ANR的风险。它也存在各种其他生命周期问题的风险。由于setListAdapter()需要在您通常在onCreate()中执行的各种其他事情之前调用,所以您可能希望将数据库访问卸载到可根据需要调用/缓存/管理的单独线程(如AsyncTask)。 AsyncTask在线程启动之前为您提供基于UI的回调,并在线程结束时为您提供基于UI的回调。 ListAdapter可以被创建和分配,而不需要任何对Cursor的引用(并且我建议你尽快解决这个问题......这似乎不是你使用自定义列表适配器的好理由,你应该管理您的数据库访问更好)。

通过活动拆解和重建来管理这个任务(想一想改变方向......)是一个完全不同的蜡球,并且已经在SO上被覆盖了。

+0

“可以创建并分配ListAdapter没有到光标任何引用(我会建议你尽快修复“。如果你看看SimpleCursorAdapter这样的东西,它需要在构造函数中使用Cursor。 – yydl 2011-06-16 05:20:03

+0

嗯:'m_listAdapter = new ArrayAdapter ((Conte XT)这个,R.layout.list_row,R.id.rowText,m_arrayList){ \t \t \t \t @覆盖 \t \t公共查看getView(INT位置,查看convertView,ViewGroup以及母公司){...}} setListAdapter (m_listAdapter);'格式不正确,但是,嘿,我分配了一个列表适配器,而没有制作游标。 – Pedantic 2011-06-16 05:23:28

+0

使用'SimpleCursorAdapter'应该认真考虑Android反模式,并从所有教程和示例代码中受到影响。 – Pedantic 2011-06-16 05:28:33

0

请将您的用户界面与后台任务分开。在后台编写游标部分,并在forground中显示任何UI或进度对话框。使用的AsyncTask此

的AsyncTask类有以下方法

1. doInBackground: Code performing long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed. 
    2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method. 
    3. onPreExecute: This method is called before doInBackground method is called. 
    4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method. 

How to use AsyncTask

感谢 迪帕克

+0

好的:在AsyncTask中获得游标后,我只是将它应用到listview中? – yydl 2011-06-16 05:40:29

+0

当支持ListAdapter的数据发生变化时,调用'm_listAdapter.notifyDataSetChanged();通常,这将与您的AyncTask中的onPostExecute()方法类似。如果你有一个足够长的查询,你真的很担心这种情况,我强烈建议你多做一些阅读。 – Pedantic 2011-06-16 05:45:42