【问题标题】:Android SQLite _id column problemAndroid SQLite _id 列问题
【发布时间】:2010-10-23 12:22:49
【问题描述】:

我是 android 新手,目前正在研究列表适配器。我知道某些类型的列表适配器需要 _id 列来处理数据。我提供了一个 _id 列,但我无法使其工作。我遵循记事本示例,所以这是我的代码:

我通过这个语句创建数据库:

private static final String DB_TABLE = "radios";
public static final String KEY_NAME = "name";
public static final String KEY_URL = "url";
public static final String KEY_ROWID = "_id";

私有静态最终字符串 DB_CREATE = "创建表" + DB_TABLE +" ("+ KEY_ROWID +" 整数主键自增," + KEY_NAME +" text not null, "+ KEY_URL +" text not null);";

使用 dbhelper 类:

 private static class DBHelper extends SQLiteOpenHelper {

    DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DB_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
        onCreate(db);
    }
}

这里我得到了 db 中的所有记录:

public Cursor getAllRadios() {
    return db.query(DB_TABLE, new String[] {KEY_ROWID,KEY_NAME,KEY_URL}, null, null, null, null, null);
}

还有我的适配器:

String[] from = new String[] { DBAdapter.KEY_NAME };
    int[] to = new int[] { R.id.text1 };

    try{
     SimpleCursorAdapter radios = new SimpleCursorAdapter(this, R.layout.list_item, cursor , from, to); 
     setListAdapter(radios);
    }
    catch(Exception e){
     e.printStackTrace();
    }

我找不到任何问题,但我仍然收到 no such column as "_id" 错误。有什么想法吗?

【问题讨论】:

    标签: android listadapter


    【解决方案1】:

    嗯,您用于创建表的 SQL 代码对我来说看起来不错(即使您可以将列名括在引号中以确保这一点)。但也许您已经有一个未升级的现有旧表?只是为了确定:增加 DB_VERSION 并再次执行。

    【讨论】:

    • 有没有办法超越系统告诉 id 列不是 _id 而是 id ?
    • 我认为没有办法 - 但除了“_id”列之外,您还可以添加自己的“id”列。它不能是主键,但您可以使其唯一并根据需要在其上创建索引。
    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多