In my Android app I have a
-
SQLiteHelper class that extends SQLIteOpenHelper, and takes care of things like table-creation and upgrades.
-
SQLiteDatasource class that performs CRUD operations on the SQLiteHelper object.
I want to pre-load one of the tables with certain items so there is something present when the user first uses the app. These items may change so I want to make them modular.
Right now I am doing it this way:
public class MyDefaults {
public static final ArrayList<HashMap<String, String>> MY_DEFAULTS;
static {
MY_DEFAULTS = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
//All the values below you change to whatever defaults you want
map.clear();
map.put(SQLiteHelper.KEY_1, "Value 1A");
map.put(SQLiteHelper.KEY_2, "Value 2A");
map.put(SQLiteHelper.KEY_3, "Value 3A");
MY_DEFAULTS.add(new HashMap<String, String>(map));
map.clear();
map.put(SQLiteHelper.KEY_1, "Value 1B");
map.put(SQLiteHelper.KEY_2, "Value 2B");
map.put(SQLiteHelper.KEY_3, "Value 3B");
MY_DEFAULTS.add(new HashMap<String, String>(map));
map.clear();
map.put(SQLiteHelper.KEY_1, "Value 1C");
map.put(SQLiteHelper.KEY_2, "Value 2C");
map.put(SQLiteHelper.KEY_3, "Value 3C");
MY_DEFAULTS.add(new HashMap<String, String>(map));
//and so on
}
}
And then in my SQLiteDatasource class I have a method that performs the insert of these default values:
public void preloadDefaults() {
mDatabase.beginTransaction();
try {
for (HashMap<String, String> map : MyDefaults.MY_DEFAULTS) {
ContentValues values = new ContentValues();
values.put(SQLiteHelper.KEY_1, map.get(SQLiteHelper.KEY_1));
values.put(SQLiteHelper.KEY_2, map.get(SQLiteHelper.KEY_2));
values.put(SQLiteHelper.KEY_3, map.get(SQLiteHelper.KEY_3));
mDatabase.insert(SQLiteHelper.SOME_TABLE, null, values);
}
}
finally {
mDatabase.endTransaction();
}
}
Is my way of doing this considered bad practice? Is there a better way to define the "defaults" that get inserted into a table after it gets created? Possibly through XML instead of a static class?
Aucun commentaire:
Enregistrer un commentaire