gpt4 book ai didi

java - 在 android 中使用简单列表项 2 时的 NPE

转载 作者:行者123 更新时间:2023-12-02 06:03:23 27 4
gpt4 key购买 nike

我试图使用简单的游标适配器将数据库中创建的两列的值放入简单列表项 2 的两个 TextView 中,但我得到了 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)

最佳答案

您的数据库尚未初始化。

此外,检查完整的堆栈跟踪也很有用。 RuntimeException 中嵌套了一个“由”异常引起的。双击 IDE 中的堆栈跟踪行将准确显示出现问题的代码行。

关于java - 在 android 中使用简单列表项 2 时的 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22480860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com