2011-04-08 116 views
1

我有一個問題,顯示從我的數據庫在列表視圖中的記錄。這是我的代碼SimpleCursorAdapter和ListView問題

public class FirstTab extends ListActivity {  


private DatabaseHelper dbhelper; 


@Override 
public void onCreate(Bundle icicle) 
{ 
super.onCreate(icicle); 

    setContentView(R.layout.first); 

    dbhelper = new DatabaseHelper(getApplicationContext()); 
    Cursor cursor = dbhelper.getAllNotes(); 
    startManagingCursor(cursor); 


    String[] columns = new String[] {DatabaseHelper.colTitle , DatabaseHelper.colDate}; 

    int[] to = new int[] { android.R.id.text1, android.R.id.text2}; 

    SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, columns, to); 

    setListAdapter(mAdapter); 
} 
} 

... 
public Cursor getAllNotes() 
{ 
    SQLiteDatabase db=this.getReadableDatabase(); 

    return db.query(noteTable, new String [] {colTitle, colDesc, colDate}, null, null, null, null, null); 

} 
... 

,如果你需要更多的,這裏是回購https://github.com/grzegorz-l/myHomeworks

當我開始我的應用程序崩潰,它在beggining(RuntimeException的)。如果我在onCreate方法中註釋2最後一行,它會運行但是不會顯示任何內容。

在此先感謝

格雷格

+0

發佈異常消息/堆棧跟蹤的詳細信息。 – superfell 2011-04-08 21:44:05

回答

2

創建SimpleCursorAdapter時,不要通過getApplicationContext()。改爲使用this,即ListActivity的上下文。

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, columns, to); 
+1

我複製了錯誤的代碼; repo中的p正確的是「this」,但是如果有這個代替getApplicationContext – Greg 2011-04-08 21:30:58

0

您的FirstTab.java文件正在擴展ListActivity。這意味着,它的佈局文件包含與Android一個ListView:ID設置爲:

android:id="@android:id/list" 

此外,您FirstTab.java有它的佈局指向note_entry.xml。它應該指向一個具有上述描述的ListView或者不被ListActivity擴展的佈局。