2011-11-21 106 views
5

嘿,我使用列表視圖來演示存儲在數據庫中的條目。我還有一個EditText元素和一個將EditText的內容添加到數據庫中的按鈕。要將視圖綁定到我使用SimpleCursorAdapter和下面填入功能的數據庫內容:使用SimpleCursorAdapter更新Android ListView

private void populate() { 
    cursor = dbAdapter.getAllItems(); 
    startManagingCursor(cursor); 

    String[] from = new String[] { DBAdapter.KEY_TASK }; 
    int[] to = new int[] { android.R.id.text1 }; 

    // Now create an array adapter and set it to display using our row 
    cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to); 
    list.setAdapter(cursorAdapter); 
} 

如果我增加了一個新的項目,通過點擊按鈕,我想刷新列表視圖但這只是與填入功能的工作原理而不是使用通用適配器功能notifyDataSetChanged();。我有錯誤還是這是刷新列表視圖的正確方法?

回答

8

你見過this,試過swap cursor的方法,還是試圖只是簡單地再次調用setAdapter()

我有一個類似的問題,我無法讓我的列表更新,我所做的只是創建一個refreshListView()方法。現在,您可以從onCreate()開始調用此函數,並且可以隨時向用戶數據庫添加一些內容。它所做的就是將listview重新綁定到遊標。通過所有的廢棄方法(requery())和notifyDataSetChanged()的問題,我決定這是最簡單的方法。

+0

只需提一下:'repery()'已被棄用。 [Documentation](http://developer.android.com/reference/android/database/Cursor.html#requery())對此有清晰的記錄。 – 87element

+0

我知道了,我沒有把這句話說得很對,重新措辭它:> – Jack

+0

嘿傑克感謝您的回覆,我發現我忘了說上面的代碼是我的'populate()'函數,我稱它爲我的'onCreate()'方法,如果我點擊「添加」按鈕。我只想知道這是否是調用此方法而不是調用基本適配器類的通用'notifyDataSetChanged()'方法的好方法。 –

2

請參考此鏈接...它就像魅力

Update SimpleCursorAdapter while maintaining scroll position in ListView

動態列表視圖上滾動我從數據庫中添加新項... 我確實錯在這裏.. 我被分配新的適配器每次爲同一個simplecursoradapter。 而不是創建新的適配器。 只是用

adapter.changecursor(newcursorValue); 
adapter.notifydatasetChanged(); 
lsMedicine1.setSelectionFromTop(lsMedicine1.getLastVisiblePosition()-20, 0); 
1

您需要notifyDataSetChanged()適配器上之前調用swapcursor()

相關問題