Data storage scheme in Android, persistence technology

There are three main ways to store data in Android: 1. File storage. 2. SharedPreference storage. 3. Database storage.

1. File Storage

Suitable for storing simple text data without any formatting

write

FileOutputStream Context.openFileOutput(String fileName, int mode);

mode mode :

  • MODE_PRIVATE Overwrite the original content when a file with the same name already exists
  • Append to end of file if MODE_APPEND already exists
  • MODE_WORLD_READABLE allows other applications to read (deprecated, deprecated in 4.2)
  • MODE_WORLD_WRITEABLE allows other applications to write (not recommended, abolished in 4.2)

Returns a FileOutputStream for writing to the file

read

FileInputStream Context.openFileInput(String fileName);

With only one parameter, returning a FileInputStream can easily get the file content

2. SharedPreferences storage

It is stored in the form of key-value pairs, supports a variety of different data types, and the data types stored and read are the same.

To store data in SharedPreferences, first get the SharedPreferences object, there are three ways to get it.

store

  • Context.getSharedPerferences(String fileName, int mode). The first parameter is the file name, the second parameter is the operation mode, and only MODE_PRIVATE is optional.
  • Activity.getDefaultSharedPerferences(int mode). This method accepts only one parameter, the operation mode.
  • PreferenceManager.getDefaultSharedPreferences(Context context), this is a static method that accepts a current context parameter and names the stored file with the package name.

There are three steps to storage

  1. Call the SharedPreferences.edit() method to get a SharedPreferences.Editor object.
  2. Add data to the SharedPreferences.Editor object, for example: .putBoolean(), .putString().
  3. Call .apply() to commit the changes

example

SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("key", "value");
editor.putBoolean("bool", true);
editor.apply();

read

Reading data from SharedPreferences is very simple, just call SharedPreferences.Editor.getString("key") to get different types of data and call different methods boolean, getBoolean.

3. SQLite database storage

A helper abstract class is needed to store with the database: SQLiteOpenHelper We need to implement a class and inherit it. Then instantiate it.

class SQLiteData extends SQLiteOpenHelper{
    public SQLiteData(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    [@Override](https://my.oschina.net/u/1162528)
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        
        // 此处添加创建数据库表的代码
    }
    [@Override](https://my.oschina.net/u/1162528)
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        
        // 此处添加更新数据库代码
    }
}

Construction method :

  • context: context, application context
  • name: the name of the database, the file /data/data/com.example.myapplication/databases/dbname.db will be generated
  • factory: Factory method, usually pass in null
  • version: version, if it is increased, onUpgrade will be executed

This takes two abstract methods, onCreate is used to execute when the database is created (if it does not exist). onUpgrade is used to execute when upgrading, when the version is increased compared to before when the class is instantiated.

instantiate, create/get database

SQLiteData db = new SQLiteData(MainActivity.this, "user.db", null, 1); // 不存在则创建
SQLiteDatabase mydb = db.getWritableDatabase();   // 返回一个 SQLiteDatabase 对象用于更新数据

insert data

Insert data by manipulating the SQLiteDatabase object returned by getWritableDatase(), insert method

ContentValues values = new ContentValues();
values.put(String key, String value);

mydb.insert(String table, String nullColumnHack, ContentValues values);
values.clear();

update data

ContentValues values = new ContentValues();
values.put(String key, T<?> value);

SQLiteDatabase.update(String table, ContentValues values, String whereClause, String[] whereArgs);

values: new value to update whereClause: constraint, where in SQL statement, example: "name=?"
whereArgs: replace? placeholder content

delete data

Deleting data is easier

SQLiteDatabase.delete(String table, String whereClause, String[] whereArgs);

Query data

The query is the most complex of all operations, with many parameters, and the query method returns a Cursor object operation to return the result.

Cursor SQLiteDatabase.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);

Parameter explanation:

  • table : table name
  • columns : specify the column names of the query
  • selection : specify the constraints of where
  • selectionArgs : the value of the constraint
  • groupBy : specify the column of group by
  • having : constraints of group by
  • orderBy : how the results are sorted

Operates on Cursor objects.

boolean Cursor.moveToFirst();   // 将游标移至第第一行
boolean Cursor.moveToNext();    
String Cursor.getString(int index);
int Cursor.getColumnIndex(String colName);  // 获取列名下标
void Cursor.close();

Use SQL directly

//添加数据
db.execSQL("insert into table(col1, col2, col3) values(?, ?, ?)", new String[]{"val1", "val2", "val3"});
//更新数据
db.execSQL("update from table set col1 = ? where col2 = ?", new String[]{"val1", "val2"});
//删除数据
db.execSQL("delete from table where col1 > ?", new String[]{"val1"});
//查询数据
db.rawQuery("select * from table", null);

(End) Blog link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324985690&siteId=291194637