More Efficient Ways To Store Information In Android Database
For a while now, I've been using JSON formatting to store information in Android applications. However, this is sometimes messy and I feel like it is inefficient in some aspects.
Solution 1:
You can store information in Android in 4 ways:
- Persisting in a custom Database
- Relational data
- Multiple instances of the same structure
- Don't lose data after the app process is killed
- Heavier operations
- Persisting in Android's Shared Preferences
- Simple data like primitive types (
boolean
,string
,int
..) that only occurs once - Don't lose data after the app process is killed
- Light operations
- Simple data like primitive types (
- Persisting in a file in the internal/external memory
- Depending on your choice, can be like 1. or 2.
- Harder to maintain than 1. or 2.
- Holding it in memory
- Data lost when your app process is killed
- Lightest of all options
Which one are you interested in?
I would recommend 1. or 2. for most cases, but i still need more info
SQLite Database (using a DAO pattern that i recommend)
DatabaseHelper.class
publicclassDatabaseHelperextendsSQLiteOpenHelper {
privatestaticfinalintDATABASE_VERSION=1;
privatestaticfinalStringDATABASE_NAME="your_app_name.db";
privatestaticfinal String TABLE_MODEL_CREATE=
"create table " + Model.TABLE_NAME
+ " ( "
+ Model.COLUMN_ID+ " integer primary key autoincrement, "
+ Model.COLUMN_SOME_INTEGER + " integer, "
+ Model.COLUMN_SOME_STRING + " text "
+ " );";
publicDatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// will run if there is no DB with your DATABASE_NAME@OverridepublicvoidonCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_MODEL_CREATE);
}
// will run if there is already a DB with your DATABASE_NAME and a lower DATABASE_VERSION than this@OverridepublicvoidonUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{
// execute all the updates you want
database.execSQL(UPGRADE_1);
database.execSQL(UPGRADE_2);
// ...
onCreate(database);
}
}
ModelDAO.class
publicclassModelDAO {
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
publicModelDAO(Context context)
{
dbHelper = newDatabaseHelper(context);
database = GarcomApplication.db;
}
publicvoidopen()throws SQLException
{
database = dbHelper.getWritableDatabase();
}
publicvoidclose()
{
dbHelper.close();
}
public Model createModel(Model model)
{
ContentValuesvalues= modelToContentValues(model);
longinsertId= database.insert(Model.TABLE_NAME, null, values);
return getModel(insertId);
}
public Model updateModel(Model model)
{
ContentValuesvalues= modelToContentValues(model);
introwsAffected= database.update(Model.TABLE_NAME, values, Model.COLUMN_ID + " = " + model.getId(), null);
if (rowsAffected > 0)
{
return getModel(model.getId());
}
returnnull;
}
publicvoiddeleteModel(Model model)
{
database.delete(Model.TABLE_NAME, Model.COLUMN_ID + " = " + model.getId(), null);
}
public Model getModel(long modelId)
{
Cursorcursor= database.query(Model.TABLE_NAME, Model.allColumns, Model.COLUMN_ID + " = " + modelId, null, null, null, null);
cursor.moveToFirst();
ModelnovoModel= cursorToModel(cursor);
cursor.close();
return novoModel;
}
public List<Model> getModelList()
{
List<Model> modelList = newArrayList<Model>();
Cursorcursor= database.query(Model.TABLE_NAME, Model.allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
Modelmodel= cursorToModel(cursor);
modelList.add(model);
cursor.moveToNext();
}
cursor.close();
return modelList;
}
private ContentValues modelToContentValues(Model model)
{
ContentValuesvalues=newContentValues();
values.put(Model.COLUMN_SOME_INTEGER, model.getSomeInteger());
values.put(Model.COLUMN_SOME_STRING, model.getSomeString());
return values;
}
private Model cursorToModel(Cursor cursor)
{
Modelmodel=newModel(cursor.getLong(0), cursor.getInt(1), cursor.getString(2));
return model;
}
}
Model.class
// when you have time, read about implementing Serializable or Parcelable in your models// it will help you to transfer this whole object throughout activities etcpublicclassModel{
publicstaticfinalString TABLE_NAME = "model";
publicstaticfinalString COLUMN_ID = "id";
publicstaticfinalString COLUMN_SOME_INTEGER = "some_integer";
publicstaticfinalString COLUMN_SOME_STRING = "some_string";
privatefinalString[] allColumns =
{
Model.COLUMN_ID,
Model.COLUMN_SOME_INTEGER,
Model.COLUMN_SOME_STRING
};
private long id;
privateInteger someInteger;
privateString someString;
// constructors, getters and setters
}
Usage:
ModelDAOmodelDAO=newModelDAO(someContext);
modelDAO.open(); // opening DB connectionModelnewModel=newModel();
ModelpersistedModel= modelDAO.createModel(newModel); // inserting a new model
Model updatedModel= modelDAO.updateModel(persistedModel); // updating a model
modelDAO.deleteModel(updatedModel); // deleting a model
modelDAO.close(); // closing DB connection (NEVER FORGET ABOUT THIS!)
// getting access to SharedPreferencesSharedPreferencesprefs=this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// reading dataIntegeryourInteger= prefs.getInteger("your_integer_name", defaultIntegerValue);
// persisting data
SharedPreferences.Editoreditor= mySharedPreferences.edit();
editor.putInteger("your_integer_name", yourInteger);
editor.commit();
Post a Comment for "More Efficient Ways To Store Information In Android Database"