我想知道如何完成某件事。我有一个包含以下结构和数据的数据库:
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 :(得分: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));
}
注意:请记住在使用后关闭光标。
为了获得更好的性能,我建议您将字段设为Integer,然后使用SparseIntArray代替HashMap Performance Benefits
希望这有帮助。