public class DrinkActivity extends AppCompatActivity {
public static final String EXTRA_DRINKID="drinkId";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
int drinkId=getIntent().getExtras().getInt(EXTRA_DRINKID);
// Drink drink =Drink.drinks[drinkId];
//
// TextView name=(TextView)findViewById(R.id.name);
// name.setText(drink.getName());
//
// TextView descriptipn=(TextView)findViewById(R.id.description);
// descriptipn.setText(drink.getDescription());
//
// ImageView photo =(ImageView)findViewById(R.id.photo);
// photo.setImageResource(drink.getImageResourceId());
// photo.setContentDescription(drink.getName());
SQLiteOpenHelper starbuzzDatabaseHelper=new StarbuzzDatabaseHelper(this);
try(SQLiteDatabase db=starbuzzDatabaseHelper.getReadableDatabase()) {
Cursor cursor=db.query("DRINK",
new String[]{"NAME","DESCRIPTION","IMAGE_RESOURCE_ID","FAVORITE"},
"_id=?",
new String[]{Integer.toString(drinkId)},
null,null,null);
if(cursor.moveToFirst()){
String nameText=cursor.getString(0);
String descriptionText =cursor.getString(1);
int photoId=cursor.getInt(2);
boolean isFavorite=(cursor.getInt(3)==1);
TextView name =findViewById(R.id.name);
name.setText(nameText);
TextView description=findViewById(R.id.description);
description.setText(descriptionText);
ImageView photo=findViewById(R.id.photo);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
CheckBox favarite=findViewById(R.id.favorite);
favarite.setChecked(isFavorite);
}
}catch (SQLiteException e){
Log.e("sqlite",e.getMessage());
Toast toast=Toast.makeText(this,"Database unavailable",Toast.LENGTH_SHORT);
toast.show();
}
}
public void onFavoriteClicked(View view) {
CheckBox favarite=(CheckBox)view;
ContentValues drinkValues=new ContentValues();
drinkValues.put("FAVORITE",favarite.isChecked());
int drinkId=getIntent().getExtras().getInt(EXTRA_DRINKID);
SQLiteOpenHelper MyHelper=new StarbuzzDatabaseHelper(this);
try{
SQLiteDatabase db=MyHelper.getWritableDatabase();
int row=db.update("DRINK",drinkValues,
"_id=?",new String[]{Integer.toString(drinkId)});
Log.d("sqlite","update row"+row);
}catch (SQLException e){
Log.e("sqlite",e.getMessage());
Toast.makeText(this,"database unavailable",Toast.LENGTH_SHORT).show();
}
}
}
显示错误:
E/SQLiteLog: (1) no such column: FAVORITE
E/sqlite: no such column: FAVORITE (code 1): , while compiling: SELECT NAME, DESCRIPTION, IMAGE_RESOURCE_ID, FAVORITE FROM DRINK WHERE _id=?
检查表的定义,没有 FAVORITE 这个字段(列)
不知道你这个问题是否已经解决, 如果还没有解决的话:在sqlite中,增(insert)删(delete)改(update)查(select)与标准sql语法是相同的。值得一提的是,每个sqlite中都有一个隐藏的表sqlite_master,记载了当前数据库中所有表的建表语句
在中,增(插入)删(删除)改(更新)查(选择)与标准SQL语法是相同的。值得一提的是,每个SQLITE中都有一个隐藏的表SQLITE_MASTER,记载了当前数据库中所有表的建表语句