[英]Updated table, but isn't returning the correct value
Probably something simple but it's taking me a long time to figure out. 可能很简单,但花了我很长时间才能弄清楚。
I want to save a rating bar rating and then load that rating when i re-open the actvity. 我想保存等级栏等级,然后在重新打开活动时加载该等级。 But it is always returning 0. 但是它总是返回0。
I have a recipe table with a rating column: 我有一个带有评分列的配方表:
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 " +
")";
I have an onRatingBarChange Listener to save the rating to table: 我有一个onRatingBarChange侦听器,将评分保存到表中:
(The values for id and rating are correct) (id和rating的值正确)
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
db.addRating(id, rating);
}
});
The addRating method in db class: db类中的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();
}
and finally, the getRating method in db class: 最后是db类中的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;
}
The returned rating is always 0, so either it is not saving properly or it is not getting the value properly. 返回的等级始终为0,因此它未正确保存或未正确获得该值。
db.rawQuery(SET_RATING, null);
You should use execSQL()
for UPDATE
queries, not rawQuery()
. 您应该将execSQL()
用于UPDATE
查询,而不是rawQuery()
。 (Or one of the convenience wrappers such as update()
.) (或便捷包装之一,例如update()
。)
rawQuery()
compiles the underlying SQL but does not execute it; rawQuery()
编译基础SQL但不执行它; execSQL()
both compiles and runs the SQL. execSQL()
编译并运行SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.