2011-06-16 51 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