2014-03-02 40 views
1

我在想如何完成某件事情。我有以下結構和數據的數據庫:通過SQLite數據庫條目填充設置變量

database.execSQL("create table records (" 
      + "_id integer primary key autoincrement," 
      + "name varchar not null," 
      + "calories integer not null," 
      + "protein integer not null," 
      + "carbs integer not null," 
      + "fat integer not null," 
      + "date integer not null" 
      + ")"); 

    database.execSQL("create table settings (" 
      + "_id integer primary key autoincrement," 
      + "field varchar not null," 
      + "value varchar not null" 
      + ")"); 

    database.execSQL("insert into settings (field, value) VALUES ('target_calories', '2700')"); 
    database.execSQL("insert into settings (field, value) VALUES ('target_protein', '200')"); 
    database.execSQL("insert into settings (field, value) VALUES ('target_carbs', '300')"); 
    database.execSQL("insert into settings (field, value) VALUES ('target_fat', '80')"); 

現在,我想在另一個活動做的就是抓住所有從設置表中的值,這樣我可以把它們比作什麼用戶進入記錄今天的表格。

所以基本上,我試圖找出搶設置並將它們轉儲到變量的最佳方式,即:

int target_calories = Integer.parseInt("2700"); 
int target_protein = Integer.parseInt("200"); 

任何幫助將不勝感激。

+0

你想查詢數據庫還是解析一個整數? –

+0

我想將設置轉儲到變量中以供在活動中使用。 – scarhand

+0

我認爲哈希映射是我在找.... – scarhand

回答

1

你需要做的是編寫一個SQL查詢以從數據庫表中獲取這些值,並將它們寫入到變量或Map中,如您在評論中所述。

Cursor cursor = database.query("settings", new String[] { "field", "value" },null, null, null, null,null); 
Map<String,Integer> settings = new HashMap<String,Integer>(); 
while (cursor.moveToNext()) { 
    settings.put(cursor.getString(0), cursor.getInt(1)); 
} 

注:記住使用後關閉遊標。

爲了更好的表現,我會建議作出整數您的域,然後使用SparseIntArray代替HashMap中的Performance Benefits

希望這有助於。