2016-11-09 62 views
0

我正在用遊標初始化一個適配器,並將適配器設置爲一個列表視圖。查詢在單獨的線程葉列表視圖爲空

DatabaseHelper dbh = new DatabaseHelper(getActivity()); 
Cursor c = dbh.getMoviesTableCursor(); 
myAdapter = new DatabaseAdapter(getActivity(), c, 0); 
listView.setAdapter(myAdapter); 

當我使查詢在dbh.getMoviesTableCursor()方法,我跑說在單獨的線程查詢

private Cursor getMoviesTableCursor(){ 

    ... 

    new Thread() { 
     @Override 
     public void run() { 
      moviesTableCursor = qb.query(db, sqlSelect, null, null, null, null, null); 

     } 
    }.start(); 

    ... 

    return moviesTableCursor; 
} 

現在我的列表視圖不顯示任何東西,與我沒有在一個新的線程運行查詢像這樣

private Cursor getMoviesTableCursor(){ 

    ... 
    moviesTableCursor = qb.query(db, sqlSelect, null, null, null, 
    ... 

    return moviesTableCursor; 
} 

任何想法爲什麼?

回答

0

是的,它按預期工作。您的query在另一個線程中運行,您的getMoviesTableCursor在UI線程中運行 - >然後getMoviesTableCursor將返回空遊標。爲了避免它,你應該重寫你的代碼,如:

final Handler handler = new Handler(); 
new Thread() { 
    @Override 
    public void run() { 
     moviesTableCursor = qb.query(db, sqlSelect, null, null, null, null, null); 
     handler.post(new Runnable() { 
     @Override 
     public void run() { 
      // use handler to avoid update UI from none-UI thread. 
      //do your update list view adapter here. 
     } 
    }); 

    } 
}.start(); 
+0

謝謝。我如何更新適配器? 'setnotifyDataSetChanged()'或'swapCursor()',因爲它們都不能工作 –

+0

交換光標在這種情況下是更好的解決方案:) –