我用sqtlite
,onCreate
和onUpgrade
创建了一个getData
数据库类。执行onCreate()
中的代码后出现的问题是,它自动跳至getData()
中的代码并执行其中的内容。我不知道为什么。我感谢所有答案
我尝试将db.close()
放在这些insert()
方法之后,但是它导致了错误
public class CookingDatabase extends SQLiteOpenHelper {
private static final String DB_NAME="Cooking";
private static final int DB_VERSION = 1;
private ArrayList<Food>foods= new ArrayList<>();
// Database Constructor
public CookingDatabase(Context context) {
super(context, DB_NAME,null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
updateDatabase(db,0,DB_VERSION) // after this line, it jumped to the code in getData();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateDatabase(db,oldVersion,newVersion);
}
private void insert(SQLiteDatabase db,String name,String recipe, int imageID, int favortie)
{
ContentValues cookingValue = new ContentValues();
cookingValue.put(DBContract.CookingDB.COLUMN_NAME,name);
cookingValue.put(DBContract.CookingDB.COLUMN_DESCRIPTION,recipe);
cookingValue.put(DBContract.CookingDB.COLUMN_IMAGEID,imageID);
cookingValue.put(DBContract.CookingDB.COLUMN_FAVORITE,favortie);
db.insert(DBContract.CookingDB.TABLE_NAME,null,cookingValue);
}
private void updateDatabase(SQLiteDatabase db,int oldVer, int newVer){
if(oldVer < 1){
try{
db.execSQL(DBContract.CookingDB.CREATE_TABLE);
insert(db,"Pizza","Bake in 10 minutes",R.drawable.pizza,0);
insert(db,"Steak","Salt and pepper",R.drawable.steak,0);
insert(db,"Sushi","Fresh Salmon",R.drawable.sushi,0);
}
catch (Exception e){
e.printStackTrace();
}
}
}
public ArrayList<Food> getData(){
SQLiteDatabase db = this.getReadableDatabase(); // it goes here
String row="select * from " + DBContract.CookingDB.TABLE_NAME+" ORDER BY "
+DBContract.CookingDB._ID +" DESC";
Cursor cursor = db.rawQuery(row,null);
if(cursor != null) {
if (cursor.moveToFirst()) {
do {
foods.add(new Food(cursor.getString(cursor.getColumnIndex(DBContract.CookingDB.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(DBContract.CookingDB.COLUMN_DESCRIPTION)),
cursor.getInt(cursor.getColumnIndex(DBContract.CookingDB.COLUMN_IMAGEID)),
cursor.getInt(cursor.getColumnIndex(DBContract.CookingDB.COLUMN_FAVORITE))));
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return foods;
}
}
我只希望它创建数据库,稍后我将调用getData()
方法
答案 0 :(得分:0)
尝试在onCreate()中的updateDatabase()方法之后添加finish()方法。
希望这会有所帮助!