Kenneth Streit
Kenneth Streit

Reputation: 1272

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. I just have a more general question: are there any more efficient ways to store information in Android applications?

Upvotes: 0

Views: 94

Answers (1)

Fernando Carvalhosa
Fernando Carvalhosa

Reputation: 1107

You can store information in Android in 4 ways:

  1. 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
  2. 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
  3. 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.
  4. 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

public class DatabaseHelper extends SQLiteOpenHelper {

   private static final int DATABASE_VERSION = 1;
   private static final String DATABASE_NAME = "your_app_name.db";
   private static final 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 "
                               + " );"; 

   public DatabaseHelper(Context context)
   {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

   // will run if there is no DB with your DATABASE_NAME
   @Override
   public void onCreate(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
   @Override
   public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
   {
      // execute all the updates you want
      database.execSQL(UPGRADE_1); 
      database.execSQL(UPGRADE_2);
      // ...
      onCreate(database);
   }
}

ModelDAO.class

public class ModelDAO {

   private SQLiteDatabase database;
   private DatabaseHelper dbHelper; 

   public ModelDAO(Context context)
   {
      dbHelper = new DatabaseHelper(context);
      database = GarcomApplication.db;
   }

   public void open() throws SQLException
   {
      database = dbHelper.getWritableDatabase();
   }

   public void close()
   {
      dbHelper.close();
   }

   public Model createModel(Model model)
   { 
      ContentValues values = modelToContentValues(model);

      long insertId = database.insert(Model.TABLE_NAME, null, values); 
      return getModel(insertId);
   }

   public Model updateModel(Model model)
   {
      ContentValues values = modelToContentValues(model);

      int rowsAffected = database.update(Model.TABLE_NAME, values, Model.COLUMN_ID + " = " + model.getId(), null);
      if (rowsAffected > 0)
      {  
         return getModel(model.getId());
      }

      return null;
   }

   public void deleteModel(Model model)
   { 
      database.delete(Model.TABLE_NAME, Model.COLUMN_ID + " = " + model.getId(), null);
   }

   public Model getModel(long modelId)
   {
      Cursor cursor = database.query(Model.TABLE_NAME, Model.allColumns, Model.COLUMN_ID + " = " + modelId, null, null, null, null);
      cursor.moveToFirst();
      Model novoModel = cursorToModel(cursor);
      cursor.close();
      return novoModel;
   }

   public List<Model> getModelList()
   {
      List<Model> modelList = new ArrayList<Model>();
      Cursor cursor = database.query(Model.TABLE_NAME, Model.allColumns, null, null, null, null, null);

      cursor.moveToFirst();
      while (!cursor.isAfterLast())
      {
         Model model = cursorToModel(cursor);
         modelList.add(model);
         cursor.moveToNext();
      }
      cursor.close();
      return modelList;
   }

   private ContentValues modelToContentValues(Model model)
   {
      ContentValues values = new ContentValues();
      values.put(Model.COLUMN_SOME_INTEGER, model.getSomeInteger());
      values.put(Model.COLUMN_SOME_STRING, model.getSomeString());

      return values;
   }

   private Model cursorToModel(Cursor cursor)
   {
      Model model = new Model(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 etc
public class Model { 

   public static final String TABLE_NAME = "model"; 

   public static final String COLUMN_ID = "id";
   public static final String COLUMN_SOME_INTEGER = "some_integer";
   public static final String COLUMN_SOME_STRING = "some_string";
   private final String[] allColumns =
   {
      Model.COLUMN_ID,
      Model.COLUMN_SOME_INTEGER,
      Model.COLUMN_SOME_STRING
   };

   private long id;
   private Integer someInteger;
   private String someString;

   // constructors, getters and setters

}

Usage:

ModelDAO modelDAO = new ModelDAO(someContext);
modelDAO.open(); // opening DB connection

Model newModel = new Model();
Model persistedModel = 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!)

Shared Preferences

// getting access to SharedPreferences
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); 

// reading data
Integer yourInteger = prefs.getInteger("your_integer_name", defaultIntegerValue);  

// persisting data
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInteger("your_integer_name", yourInteger);
editor.commit();

Upvotes: 1

Related Questions