2011-07-10 35 views
0

我剛開始使用Android開發,並且正在構建一個使用ListActivitySQLiteDatabaseSimpleCursorAdapter的簡單應用程序。每當數據改變時新的SimpleCursorAdapter?

在Android開發人員網站上有一個示例項目,演示SimpleCursorAdadpter的使用情況。縱觀實施,只要底層數據庫被修改爲某個用戶操作結果,ListActivity明確要求下面的函數「刷新」名單:

private void fillData() { 
    // Get all of the rows from the database and create the item list 
    mNotesCursor = mDbHelper.fetchAllNotes(); 
    startManagingCursor(mNotesCursor); 

    // Create an array to specify the fields we want to display in the list (only TITLE) 
    String[] from = new String[]{NotesDbAdapter.KEY_TITLE}; 

    // and an array of the fields we want to bind those fields to (in this case just text1) 
    int[] to = new int[]{R.id.text1}; 

    // Now create a simple cursor adapter and set it to display 
    SimpleCursorAdapter notes = 
     new SimpleCursorAdapter(this, R.layout.notes_row, mNotesCursor, from, to); 
    setListAdapter(notes); 
} 

它看起來像一個新的SimpleCursorAdapter創建的每個時間並與setListAdapter()綁定在視圖上。這是最好的/最乾淨的實施?事實上,這是在Android網站的藉口它很多的可信度,但我看着CursorAdapter文檔,看到有一個changeCursor()方法,似乎使自己比上面的一個更乾淨的實現,但我只是不確定可能看起來像什麼。

也許我只是在煩惱什麼,但是來自C/C++世界,看到每次從數據庫插入/刪除一行時創建的這個「新」對象似乎有點過分。

+0

SimpleCursorAdapter應該總是隻創建一次......只要底層數據庫發生變化,就沒有必要創建適配器....而不是創建全新的適配器.... changeCursor()或者requery()是最好的選項。我也想知道他們爲什麼這樣做。 – Gopal

回答

0

是的,你是對的。你可以看到很多次。對於列表始終在onResume中創建時可能不會產生任何問題的小列表。但這不是一種好風格。您可以使用cursor.changeCursor()或adapter.notifyDataSetChanged()。

+0

我已決定重構代碼,以使'SimpleCursorAdapter'實例現在成爲ListActivity類的成員,並在onCreate()方法中實例化(使用空遊標)。然後,每當數據集發生變化(或第一次需要填充列表)時,我所有的實用函數都會重新查詢數據庫並返回一個新的「Cursor」實例。然後,我在適配器上調用activity上的'startManagingCursor()'方法和傳遞新創建的遊標對象上的'changeCursor()'方法。 –

相關問題