2011-04-08 114 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扩展的布局。