Android ListView数据库异常

2023-12-21

我一直是一个顽皮的男孩,我从 Android 开发者网站的官方记事本应用程序复制了一个方法,这是我的课程:

package com.example.prva;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;


public class ListView extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        fillData();
        }

    private void fillData() {
        // Get all of the notes from the database and create the item list
        Cursor c = DatabaseManager.getAllData();
        startManagingCursor(c);

        String[] from = new String[] { DatabaseManager.TABLE_COLUMN_ONE };
        int[] to = new int[] { R.id.text1 };

        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
        setListAdapter(notes);
    }
    }

当我尝试运行此 ListActivity 时,出现此错误:

01-31 02:39:14.259: E/AndroidRuntime(1845): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prva/com.example.prva.ListView}: java.lang.IllegalArgumentException: column '_id' does not exist

现在我明白了这一点,因为它是真的,我的数据库中没有 _id 列(记事本应用程序数据库有它并使用它,但我有自己的数据库),我只是不明白我的 ListActivity 中提到的该列在哪里班级?它是从哪里调用的,所以会出现错误?


请参阅文档游标适配器 http://developer.android.com/reference/android/widget/CursorAdapter.html:

游标必须包含名为 _id 的列,否则此类将无法工作。

在您的代码中,您使用 SimpleCursorAdapter,它是一个派生类,因此看来此语句适用。

游标就像迭代器或指针,它们只包含一种遍历数据的机制,它们本身不包含列。

From 另一个文档 http://developer.android.com/guide/topics/providers/content-provider-creating.html#ContentURI,你可以更好地理解上面的说法:

处理内容 URI ID

按照惯例,提供程序通过以下方式提供对表中单行的访问: 接受内容 URI,其末尾的行具有 ID 值 URI。同样按照惯例,提供程序将 ID 值与表的 ID 值进行匹配 _ID 列,并对匹配的行执行请求的访问。

此约定促进了应用程序访问的通用设计模式 一个提供者。该应用程序对提供商进行查询并显示 使用 CursorAdapter 在 ListView 中生成 Cursor。定义 CursorAdapter 的要求 Cursor 中的列之一为 _ID。

有几种方法可以帮助您解决问题:

  1. 在表中添加“_id”列。

  2. 使用别名来获取光标。例如:

    从 TABLE1 中选择 someid 作为 _id、名称、编号;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android ListView数据库异常 的相关文章

随机推荐