0

正在处理的应用程序使用静态数据而不是动态数据。因此,由于这种性质,我正在尝试创建一个函数,该函数将以一种相当有效的方式填充数据库,而不是编写

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;
}
4

1 回答 1

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);
}
于 2013-09-18T07:15:25.360 回答