Android - 填充ListView SQLite,游标空指针

时间:2015-03-06 19:48:24

标签: android android-fragments android-listview android-sqlite

我有两个表atm,用户和备注。我正在尝试检索属于用户的数据。因此,列出的所有数据必须由原始用户拥有,并且仅向他显示。我在Databasehelper中创建了我的表。 我创建了一个控制notes表的新类。在listNotes()中,我想遍历游标行并获取用户拥有的所有数据。我正确地查询了吗?

// Listing all notes

public Cursor listNotes() {

    Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    db.close();
   return c;

 }

然后我想显示在listview中收集的光标数据

public void populateList(){

    Cursor cursor = control.listNotes();
    getActivity().startManagingCursor(cursor);

    //Mapping the fields cursor to text views
    String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
    int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
    adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);

    //Calling list object instance
    listView = (ListView) getView().findViewById(android.R.id.list);
    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);
}

2 个答案:

答案 0 :(得分:0)

您没有创建NOTE_TABLE权利 你错过了一个空格和一个逗号

+ COLUMN_DATE + "DATETIME DEFAULT CURRENT_TIMESTAMP"

必须是

+ COLUMN_DATE + " DATETIME DEFAULT CURRENT_TIMESTAMP,"

答案 1 :(得分:0)

这里有两个问题:

一个是你错过了一个逗号(在之前的答案中指定的时间戳之后)。

您遇到的另一个错误是使用SimpleCursorAdapter时,您需要确保Projection字符串数组包含唯一索引行的内容,这必须是名为“_id”的整数列。 SQLite已经为此内置了一个功能,并为此提供了一个名为“_id”的列(但是您可以拥有自己的整数列,您可以将其重命名为_id)。要解决此问题,请将投影字符串数组更改为:

new String[] {"ROW_ID AS _id", help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}

我猜NullPointerException源于此(但没有我不确定的堆栈跟踪)。