我尝试根据数据库是否存在来创建一个切换到2个活动之一的按钮。我已经创建了一个databasecheckhelper,但由于某种原因,即使数据库存在,它仍然会发出错误。
单击按钮时的代码:
public void open_my_training(View view) {
Intent intent;
boolean databaseExists = checkDatabase.checkDB(this);
if(databaseExists){
intent = new Intent(this, a.class);
}else{
intent = new Intent(this, b.class);
}
startActivity(intent);
}
帮助者
public class checkDatabase {
public static boolean checkDB(Context context) {
File dbFile = context.getDatabasePath("database.db");
return dbFile.exists();
}
}
谁能告诉我我做错了什么?
编辑:
由于代码似乎很好,我将添加用于创建数据库的代码:
public void save_training(View view) {
CheckBox box1 = (CheckBox) findViewById(R.id.box1);
CheckBox box2 = (CheckBox) findViewById(R.id.box2);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
String spinner1 = spinner1.getSelectedItem().toString();
createDatabase();
addTraining(box1.isChecked(), box2.isChecked(), spinner1);
}
private void createDatabase() {
try {
trainingDB = this.openOrCreateDatabase("database.sqlite", MODE_PRIVATE, null);
trainingDB.execSQL("CREATE TABLE IF NOT EXISTS table1" + "(id integer primary key," +
"box1 boolean, box2 boolean, + "spinner1 VARCHAR);");
}
private void addTraining(boolean box1Checked, boolean box2Checked, String spinner1) {
trainingDB.execSQL("INSERT INTO table1 (box1, box2, spinner1) VALUES ('"+ box1Checked + "', '" +
box2Checked + "', '" + spinner1 + "');");
}
答案 0 :(得分:1)
替换
File dbFile = context.getDatabasePath("database.sqlite");
而不是
File dbFile = context.getDatabasePath("database.db");