我想随机获取随机ID然后我正在尝试获取WORDTR和WORDEN的索引但不能这样做。请帮助我。
public class DatabeseHelper extends SQLiteOpenHelper {
public DatabeseHelper(Context c){
super(c,"WORDS",null,1);
SQLiteDatabase db =this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="create table WORDS(ID integer primary key autoincrement,WORDTR TEXT,WORDEN TEXT)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS WORDS");
onCreate(db);
}
public Cursor getDataRandom(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from ID ORDER BY RANDOM() LIMIT 1 ",null);
cursor.moveToFirst();
int id = cursor.getInt(cursor.getColumnIndex("ID"));
return cursor;
答案 0 :(得分:1)
表名是" WORDS"当你创建表时。但是你试图从表名" ID"中获取数据。在任何地方都不存在。
正确的代码是
public Cursor getDataRandom(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from WORDS ORDER BY RANDOM() LIMIT 1 ",null);
cursor.moveToFirst();
int id = cursor.getInt(cursor.getColumnIndex("ID"));
return cursor;
}
答案 1 :(得分:0)
您在代码中遇到很多错误,请参阅以下带注释的代码
公共类DatabeseHelper扩展了SQLiteOpenHelper {
public DatabeseHelper(Context c){
super(c,"WORDS",null,1);
// SQLiteDatabase db =this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="create table WORDS(ID integer primarykey autoincrement,WORDTR TEXT,WORDEN TEXT)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS WORDS");
onCreate(db);
}
选择随机数据。
public Cursor getDataRandom(){
SQLiteDatabase db = this.getWritableDatabase();
// select * from WORDS not a ID
Cursor cursor = db.rawQuery("select * from WORDS ORDER BY RANDOM() LIMIT 1 ",null);
cursor.moveToFirst();
// id is not used,not need to declare
int id = cursor.getInt(cursor.getColumnIndex("ID"));
// return a id not a cursor
return cursor;
}
答案 2 :(得分:0)
public DatabeseHelper(Context c){
super(c,"WORDS",null,1);
SQLiteDatabase db =this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="CREATE TABLE IF NOT EXISTS " + WORDS+
"( " +
"ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, " +
"WORDTR TEXT, WORDEN TEXT);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS WORDS");
onCreate(db);
}
public int getDataRandom(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from WORDS ORDER BY RANDOM() LIMIT 1 ",null);
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex("ID"));
} while (cursor.moveToNext());
return id;