在Android数据库中存储信息的更有效方法

时间:2022-10-17 14:51:18

For a while now, I've been using JSON formatting to store information in Android applications.

有一段时间了,我一直在使用JSON格式在Android应用程序中存储信息。

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?

然而,这有时是凌乱的,我觉得它在某些方面效率低下。我只是有一个更普遍的问题:是否有更有效的方法在Android应用程序中存储信息?

1 个解决方案

#1


1  

You can store information in Android in 4 ways:

您可以通过4种方式在Android中存储信息:

  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. 持久化自定义数据库关系数据同一结构的多个实例在应用程序进程被杀死后不会丢失数据更重的操作

  3. Persisting in Android's Shared Preferences
    • Simple data like primitive types (boolean, string, int..) that only occurs once
    • 简单数据,如原始类型(boolean,string,int ..),只发生一次

    • Don't lose data after the app process is killed
    • 应用程序进程终止后不要丢失数据

    • Light operations
  4. 坚持使用Android的共享首选项简单数据,如原始类型(boolean,string,int ..),只发生一次在应用程序进程被杀后不丢失数据轻量级操作

  5. Persisting in a file in the internal/external memory
    • Depending on your choice, can be like 1. or 2.
    • 根据您的选择,可以是1.或2。

    • Harder to maintain than 1. or 2.
    • 比1或2更难维持。

  6. 保留内部/外部存储器中的文件根据您的选择,可以是1.或2.比1或2更难维护。

  7. Holding it in memory
    • Data lost when your app process is killed
    • 应用程序进程被终止时数据丢失

    • Lightest of all options
    • 最轻的选择

  8. 将其保存在内存中当您的应用程序进程被杀死时数据丢失最轻的选项

Which one are you interested in?

你对哪一个感兴趣?

I would recommend 1. or 2. for most cases, but i still need more info

在大多数情况下,我会建议1.或2.但我仍然需要更多信息


SQLite Database (using a DAO pattern that i recommend)

SQLite数据库(使用我推荐的DAO模式)

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

#1


1  

You can store information in Android in 4 ways:

您可以通过4种方式在Android中存储信息:

  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. 持久化自定义数据库关系数据同一结构的多个实例在应用程序进程被杀死后不会丢失数据更重的操作

  3. Persisting in Android's Shared Preferences
    • Simple data like primitive types (boolean, string, int..) that only occurs once
    • 简单数据,如原始类型(boolean,string,int ..),只发生一次

    • Don't lose data after the app process is killed
    • 应用程序进程终止后不要丢失数据

    • Light operations
  4. 坚持使用Android的共享首选项简单数据,如原始类型(boolean,string,int ..),只发生一次在应用程序进程被杀后不丢失数据轻量级操作

  5. Persisting in a file in the internal/external memory
    • Depending on your choice, can be like 1. or 2.
    • 根据您的选择,可以是1.或2。

    • Harder to maintain than 1. or 2.
    • 比1或2更难维持。

  6. 保留内部/外部存储器中的文件根据您的选择,可以是1.或2.比1或2更难维护。

  7. Holding it in memory
    • Data lost when your app process is killed
    • 应用程序进程被终止时数据丢失

    • Lightest of all options
    • 最轻的选择

  8. 将其保存在内存中当您的应用程序进程被杀死时数据丢失最轻的选项

Which one are you interested in?

你对哪一个感兴趣?

I would recommend 1. or 2. for most cases, but i still need more info

在大多数情况下,我会建议1.或2.但我仍然需要更多信息


SQLite Database (using a DAO pattern that i recommend)

SQLite数据库(使用我推荐的DAO模式)

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