Populating settings variables via SQLite database entries

I am wondering how to accomplish something. I have a database with the following structure and data:

    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')");

Now, what I want to do in another activity is grab all of the values from the settings table so I can compare them to what a user enters into the records table for today.

So basically, I'm trying to figure out the best way to grab the settings and dump them into variables, i.e.:

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

Any help would be greatly appreciated.

Answers


What you need to do is to write a SQL Query to get out these values from your database table and write them to your variables or a Map as you said in your comment.

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

Note: Keep in mind to close cursor after use.

For better performance, I would recommend to make your field as Integer and then use SparseIntArray instead of HashMap for Performance Benefits

Hope this helps.


Need Your Help

Slightly overlay an image over <td> HTML

html css html5 asp.net-mvc-4 c#-4.0

I have the following HTML markup which is used to display a list of product categories

Broadcast Receiver listening to text selection

android broadcastreceiver intentfilter

Is it possible to define a broadcast receiver that listens for text selection made on any application

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.