可能是一件简单的事情,但我花了很长时间才弄明白。
我想保存评级栏评级,然后在重新打开活动时加载该评级。但它总是返回0.
我有一个带有评级栏的食谱表:
final String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPES + "(" +
RECIPE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RECIPE_NAME + " TEXT, " +
RECIPE_INSTRUCTIONS + " TEXT, " +
RECIPE_RATING + " FLOAT " +
")";
我有一个onRatingBarChange侦听器将评级保存到表:
(id和评级的值是正确的)
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
db.addRating(id, rating);
}
});
db class中的addRating方法:
public void addRating(int id, float rating) {
String SET_RATING =
"UPDATE " + TABLE_RECIPES +
" SET " + RECIPE_RATING + " = " + rating +
" WHERE " + RECIPE_ID + " = " + id;
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery(SET_RATING, null);
db.close();
}
最后,db class中的getRating方法:
public float getRating(int id) {
String GET_RATING =
"SELECT " + RECIPE_RATING +
" FROM " + TABLE_RECIPES +
" WHERE " + RECIPE_ID + " = " + id;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(GET_RATING, null);
c.moveToFirst();
float rating = c.getFloat(0);
Log.i("getRating", "gotRating: " + rating);
return rating;
}
返回的评级始终为0,因此要么没有正确保存,要么没有正确获得该值。
答案 0 :(得分:1)
db.rawQuery(SET_RATING, null);
您应该execSQL()
使用UPDATE
查询,而不是rawQuery()
。 (或其中一个便利包装,如update()
。)
rawQuery()
编译底层SQL但不执行它; execSQL()
编译并运行SQL。