2012-07-29 62 views
-1

我有一個onCreate()方法,它使用datasource.open()datasource.close()。如果在onCreate()的末尾發出datasource.close();,我的ListView SimpleCursorAdapter始終爲空。關閉數據庫和光標與ListView

如果我從onCreate()的末尾刪除datasource.close();,則會填充ListView。

我無法弄清楚爲什麼這是我的生活。

任何人都有任何文件說明爲什麼發生這種情況?

示例代碼:

@Override 
protected void onCreate(Bundle bundle) { 
    super.onCreate(bundle); 

    Bundle extras = getIntent().getExtras(); 
    id = extras.getLong("extraID"); 

    setContentView(R.layout.main); 

    datasource = new SMSDataSource(this); 
    datasource.open(); 

    Cursor groupCursor = datasource.queryByGroup(long id); 

    contactAdapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_list_item_2, // Use a template 
      // that displays a 
      // text view 
      getCur, // Give the cursor to the list adapter 
      new String[] { DBManagement.CONTACTS_COLUMN_NAME, 
      DBManagement.CONTACTS_COLUMN_NUMBER }, // Map the NAME 
      // column in the 
      // people database to... 
      layouts); // The "text1" view defined in 
    // the XML template 

    list = (ListView) findViewById(android.R.id.list); 
    list.setAdapter(contactAdapter); 

    registerForContextMenu(list); 

    groupCursor.close(); 
    datasource.close(); 
} 
+0

爲什麼使用Content Provider?由此可以使用光標。 – 2012-07-29 05:52:53

+0

這取決於你的光標對象的範圍。發佈我們的代碼2得到正確的理由.. – Jayabal 2012-07-29 06:41:16

+0

添加代碼。這是正常的通用listview適配器連接使用簡單的遊標適配器 – 2012-07-29 15:49:31

回答

1

如果你想手動管理你的光標,你應該在你的活動的onStop然後requery()恢復中調用deactiveate()

但是,我會簡單地使用Activity.startManagingCursor()這將爲你照顧這個。此方法被標記爲已棄用,因此如果您想完全按照Google建議的方式執行操作,則需要使用CursorLoader類來異步處理遊標。坦率地說,除非你的數據庫真的很大,並且/或者你的查詢運行速度很慢,否則使用不推薦使用的方法沒有什麼壞處,它不會持續一段時間。

+1

StartMAnagingCursor和重新查詢,現在不推薦使用。我使用Adapter.changeCursor來替換重新查詢。 – 2012-07-29 17:45:01

+0

您正在以非常錯誤的方式使用'changeCursor'。 – 2012-07-29 18:15:16

0

其實我覺得datasource.close()方法調用應該放置的地方在onPause()onStop()onDestroy methods..But沒有必要 如果你將張貼一些代碼片段,我可以可能會提供更準確的答案。

+0

如果我這樣做,我得到了臭名昭着的'關閉()從來沒有調用光標或數據庫「 – 2012-07-29 15:50:15