我试图使用简单的游标适配器将数据库中创建的两列的值放到简单列表项2的两个文本视图中,但我得到的是NPE。
请帮忙。
问候
我的代码是:
class NotesList extends ListActivity{
private DataSource datasource;
ArrayAdapter<Message> adapter;
Cursor cursors = null;
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datasource = new DataSource(this);
datasource.open();
// List<Message> values = datasource.getAllMessages();
// adapter = new ArrayAdapter<Message>(this, android.R.layout.simple_list_item_1, values);
// setListAdapter(adapter);
String queryz = "SELECT " + MySQLiteHelper.COLUMN_ID + "," + MySQLiteHelper.COLUMN_MESSAGE+ " FROM " + MySQLiteHelper.TABLE_NAME ;
cursors = database.rawQuery(queryz, null);
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
cursors, // Pass in the cursor to bind to.
new String[] {MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MESSAGE}, // Array of cursor columns to bind to.
new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
setListAdapter(adapter);
}
@Override
public void onResume() {
datasource.open();
super.onResume();
}
@Override
public void onPause() {
datasource.close();
super.onPause();
}
Datasource和Mysqlitehelper是我的类的名称.MySqliteHelper类创建了两列id和notes。 Logcat是:
03-19 01:15:32.557: E/AndroidRuntime(10579): FATAL EXCEPTION: main
03-19 01:15:32.557: E/AndroidRuntime(10579): java.lang.RuntimeException: Unable to start activity ComponentInfo{soft.b.notes/soft.b.notes.NotesList}: java.lang.NullPointerException
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.access$600(ActivityThread.java:122)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.os.Looper.loop(Looper.java:137)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.main(ActivityThread.java:4340)
答案 0 :(得分:1)
您的database
未初始化。
此外,检查完整堆栈跟踪很有用。由&#34;引起的&#34;嵌套在RuntimeException
中的异常。双击IDE中的堆栈跟踪行将准确显示出现问题的代码行。
答案 1 :(得分:1)
您正在一个null的数据库上运行rawQuery。我没有看到你真正为你的数据库变量获得SQLiteDatabase的任何地方。