正在处理的应用程序使用静态数据而不是动态数据。因此,由于这种性质,我试图创建一个函数,以相当有效的方式填充数据库,而不是编写
INSERT INTO table (id, name, description, category) VALUES ('1', 'ABC', 'XYZ', 'TRY');
功能如下:
// Adding medicine entry
public void addMedicine(String brand, String description, String category) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_BRAND, med.getBrand());
values.put(KEY_CATEGORY, med.getCategory());
values.put(KEY_DESCRIPTION, med.getDescription());
db.insert(TABLE_MEDICINE, null, values);
db.close();
}
//populating the database
public void populateDB(){
this.addMedicine(new Medicines("ABC", "XYZ", "ABC"));
this.addMedicine(new Medicines("Mosard Tab", "Each Film coated tablet contains: Mosapride Citrate Dihydrate - 5mg JP eqv. To Mosapride citrate", "Posted under Tablets"));
}
最后:
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_MED_TABLE = "CREATE TABLE " + TABLE_MEDICINE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_BRAND + " TEXT,"
+ KEY_DESCRIPTION + " TEXT," + KEY_CATEGORY + " TEXT )";
db.execSQL(CREATE_MED_TABLE);
populateDB();
}
但是这给了我以下错误:
09-18 12:02:29.639: E/AndroidRuntime(13139): FATAL EXCEPTION: main
09-18 12:02:29.639: E/AndroidRuntime(13139): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geneticalabs/com.geneticalabs.TrailDB}: java.lang.IllegalStateException: getDatabase called recursively
有人可以帮忙吗?或者建议如何以非平凡的方式填充数据库的任何其他选择。
此外,我使用以下函数将数据提取到我的应用程序:
//Getting all the medical entries
public List<Medicines> getAll(){
List<Medicines> medList = new ArrayList<Medicines>();
//Select all query
String query = "SELECT * FROM "+TABLE_MEDICINE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(query, null);
if(c.moveToFirst()){
do{
Medicines med = new Medicines();
med.setID(Integer.parseInt(c.getString(0)));
med.setBrand(c.getString(1));
med.setDescription(c.getString(2));
med.setCategory(c.getString(3));
medList.add(med);
}while(c.moveToNext());
}
return medList;
}
答案 0 :(得分:2)
尝试重新使用您的数据库实例,而不是使用this.getWritableDatabase()
:
public void addMedicine(SQLiteDatabase db, String brand, String description, String category) {
// all your code
// but remove this call: db.close();
}
public void populateDB(SQLiteDatabase db){
this.addMedicine(db, new Medicines("ABC", "XYZ", "ABC"));
this.addMedicine(db, new Medicines("Mosard Tab", "Each Film coated tablet contains: Mosapride Citrate Dihydrate - 5mg JP eqv. To Mosapride citrate", "Posted under Tablets"));
}
@Override
public void onCreate(SQLiteDatabase db) {
// your code
populateDB(db);
}