2010-04-24 55 views
2

我想刷新Listview項目。這些項目從SQLite數據庫填充。我的代碼如下Android ListView與SQLite

public class Weeve extends Activity { 
     private String[] lv_arr; 
    protected ListView CView; 
    private DBAdapter mDbHelper; 

公共無效的onCreate(捆綁savedInstanceState){

super.onCreate(savedInstanceState); 

    mDbHelper = new DBAdapter(this); 
    mDbHelper.open(); 

    Cursor c = mDbHelper.getAll(); 
    if (c.getCount() > 0) 
    {if (c.moveToFirst()) 
    { 
     ArrayList strings = new ArrayList(); 
     do {      
      String mC = c.getString(0); 
      strings.add(mC); 

     } while (c.moveToNext()); 
     lv_arr = (String[]) strings.toArray(new String[strings.size()]); 
    } 
    } 
    else Toast.makeText(this, 
      "No more Records", 
      Toast.LENGTH_SHORT).show(); 
    c.close(); 

    ListView CView = new ListView(this); 
    CView.setAdapter(new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, lv_arr));  
    setContentView(CView);}} 

我想提神添加,更新或刪除SQLite表後,該列表視圖。這些操作由內容或選項菜單調用。我試圖將這些代碼創建爲分離的函數,並在每次操作後調用它。但不能。我認爲setContentView(CView)語句。

我也嘗試使用SimpleCursorAdapter,比如來自Android.com的記事本示例。我有線程錯誤。幫我。

回答

2

你可以使用Adapter.notifyDataSetChanged()來做到這一點。

但是,我發現你的代碼略微偏離。您使用遊標從數據庫中提取行,只是爲行值創建一個新的ArrayAdapter。爲什麼不使用CursorAdapter來支持你的列表?這就是它的意思。

+0

我可以爲我的活動獲取示例SimpleCursorAdapter代碼嗎? – soclose 2010-04-25 05:14:25

0

確保您的所有活動都在清單中

+0

如果我們使用SimpleCursorAdapter,我們必須添加主鍵列'_id'。我得到的錯誤是由這個列名'_id'造成的。 – soclose 2010-07-12 14:33:42