首页 文章

Android SQLite _id列问题

提问于
浏览
1

我是android的新手,现在正在使用列表适配器 . 我知道某种类型的列表适配器需要_id列来处理数据 . 我提供了一个_id列,但我无法使其工作 . 我按照记事本示例,所以这是我的代码:

我通过以下语句创建db:

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";

private static final String DB_CREATE =“create table”DB_TABLE“(”KEY_ROWID“整数主键自动增量,”KEY_NAME“文本不为空,”KEY_URL“文本不为空);”;

使用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" 错误 . 有任何想法吗?

1 回答

  • 1

    嗯,你创建表的SQL代码看起来很好(即使你可以把你的列名用引号括起来,只是为了确定) . 但也许你已经有一个未升级的现有旧表?只是为了确定:增加DB_VERSION并再次执行 .

相关问题