我正在爲我正在開發的Android應用創建數據庫。我試圖學習如何遵循正確的標準進行編碼,並且我在DbHelper類的onCreate方法中讀取了數據庫被創建的地方。我還讀到它在onCreate方法中應該用數據填充數據庫。它是否正確?如果是這樣,我如何傳遞一個對象到onCreate方法,以便我可以遍歷它並填充數據庫?Android SQLite:調用onCreate方法並傳入一個對象
public class DbHelper extends SQLiteOpenHelper
{
private static String DATABASE_NAME = "FodoSubstitutes.db";
private static String FOOD_TABLE = "Food";
//Creates the database with db name and calls onCreate().
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db)
{
//System.out.println("in onCreate");
//assocID food healthierFood category description count submittedBy
String sql = "CREATE TABLE IF NOT EXISTS " + FOOD_TABLE +
"(Food_ID integer primary key, " +
"Food_Name string not null, " +
"Food_Aliases string, " +
"Hints string, " +
"Category string, " +
"Subcategory string, " +
"Description string, " +
"Submission_ID int, " +
"Comment_ID int, " +
"Count int); ";
db.execSQL(sql);
}
}
我的想法是做這樣的事情。
DbHelper.onCreate(Food myFoodObj);
但這不起作用。有什麼想法嗎?這是一種簡單明顯的東西,我可以忽略。
將其分成兩部分。第一部分:創建數據庫。第二部分:創建一個方法,用你的對象更新數據庫,比如說創建一個名爲'addFood'的方法,在那裏你執行一個合適的'db.execSQL','db。查詢「等等。您可能還需要一些幫助器方法來檢查數據庫是否存在等等。另外,請記住:http://stackoverflow.com/a/7164505/429047 – 2012-03-07 04:34:09