SoFunction
Updated on 2025-04-06

Four Android data storage methods

Android provides the followingFour storage methods

  • SharePreference
  • SQLite
  • File
  • ContentProvider

Data in Android system is basically private and is generally stored in the "data/data/package name" directory. If you want to implement data sharing, the correct way is to use ContentProvider.

SharedPreference
SharedPreference is a lightweight data storage method, which is actually based on the "key-value" key-value pair data stored in XML files. It is usually used to store some configuration information of the program. It is stored in the "data/data/package name/shared_prefs directory.
SharedPreference itself can only obtain data and does not support storage and modification. Storage and modification must be implemented through Editor objects.

1) Modify and store data

  1. Get SharedPreference object according to the getSharedPreferences(key, [mode]) method of Context;
  2. Use the editor() method of SharedPreference to get the Editor object;
  3. Through the Editor's putXXX() method, the key-value pairs are stored;
  4. Submit the data to SharedPreference through the Editor's commit() method.

Comprehensive example:

//Set the value in the singleton, and then write the value into SharedPreference
 private String setCityName(String _cityName){
  ().setCityName(_cityName);
  
  Context ctx =;
  SharedPreferences sp =("CITY", MODE_PRIVATE);
  Editor editor=();
  ("CityName", ().getCityName());
  ();
  
  return ().getCityName();
 }

2) Obtain data

  1. Also obtain SharedPreference object based on the Context object;
  2. Directly use the getXXX(key) method of SharedPreference to get data.

Comprehensive example:

 //Follow from the singleton, if it does not exist, read in SharedPreferences
 private String getCityName(){
  String cityName = ().getCityName();
  if(cityName==null ||cityName==""){
   Context ctx =;
   SharedPreferences sp =("CITY", MODE_PRIVATE);
   ().setCityName(("CityName", "Guangzhou"));
  }
  return ().getCityName();
 }

Notice
In the getSharedPrerences(key, [mode]) method, the first parameter actually corresponds to the XML file name, and data with the same key will be saved to the same file.
When using the getXXX(key) method of SharedPreference to get data, if the key does not exist, there will be no errors and none will be returned. It is recommended to specify the default value when using getXXX().

SQLite
SQLite is a lightweight relational database. Since it is a relational database, it is actually similar to mysql and SQL servers in operation.
One thing to note is that SQLite only has five types: NULL, INTEGER, REAL (floating point number), TEXT (string) and BLOB (big data), and there are no BOOLEAN and DATE types.

1) Create a database
Created by openOrCreateDatabase(String path, factory) method, if the library has been created, the database is opened.

Copy the codeThe code is as follows:
SQLiteDatabase db =("test_db.db", Context.MODE_PRIVATE, null);

2) Create a table
SQLiteDatabase does not provide a method to create tables, so it depends on the execSQL() method to implement it. It is also known that execSQL() is used to directly execute SQL.
Copy the codeThe code is as follows:
String sql="create table t_user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL,password TEXT NOT NULL)";
(sql);
 

increase
Use SQLiteDatabase's insert(String table, String nullColumnHack, ContentValues ​​values) method to insert data. The ContentValues ​​class, similar to Map in Java, saves data in key-value pairs.

ContentValues values=new ContentValues();
("name", "liangjh");
("password", "123456");
("t_user", "id", values);

delete
Deleting data is more direct. Use SQLiteDatabase's delete(String table, String whereClause, String[] whereArgs) implementation. If you don't want to write the parameters in whereArgs, you can directly write the conditions in whereClause.

// Method 1: Write the conditions directly into the conditions (I personally think it is easy to inject, but in fact the data is all on the client side, so there is no security at all)("t_user", "id=1", null);
// Method 2: Write separately, it feels safer("t_user", "name=? and password =?", new String[]{"weiyg","112233"});

check
There are two methods for query, query() and rawQuery(). The difference is that query() extracts the parameters in SQL from the corresponding parameters of query(). Please refer to the following example.

// Use rawQuery// Cursor c = ("select * from t_user", null);
// ("select * from t_user where id=1", null);
// ("select * from t_user where id=?", new String[]{"1"});
 
// Use query()Cursor c = ("t_user", new String[]{"id","name"}, "name=?", new String[]{"weiyg"}, null, null, null);
();
while(!()){
 String msg="";
 for(int i=0,j=();i<j;i++){
  msg+="--"+(i);
 }
 ("SQLite", "data:"+msg);
 ();
}

change
Use SQLiteDatabase's update(String table, ContentValues ​​values, String whereClause, String[] whereArgs) to modify the data. whereClause and whereArgs are used to set their conditions. The ContentValues ​​object is data.

ContentValues values=new ContentValues();
("password", "111111");
// Method 1 The condition is written in the string("t_user", values, "id=1", null);
// Method 2: The condition and string are separated("t_user", values, "name=? or password=?",new String[]{"weiyg","123456"});

other
Whenever you open the database, remember to close it.

()
In addition, beginTransaction() and endTransaction() can be used to set transactions.

File
File storage method, I have mentioned a long time ago, and I will not explain it here.

ContentProvider
ContentProvider is more complex than other methods, and of course its functions are also a revolutionary change compared to other methods. It can implement data operations across applications. Use the delete, update, insert, query and other methods of the ContentResolver object to operate the ContentProvider object, so that the ContentProvider object method can operate the data. The implementation method is:

Define a ContentProvider in Program A and overload its methods such as adding, deleting, searching and modifying;
Register ContentProvider in Program A;
In program B, the ContentResolver and Uri are used to obtain the data of ContentProvider, and the data is also obtained by using Resolver's addition, deletion, and revision method.
1) Define a Provider in Program A
Create a new class, inherit ContentProvider, and overload its delete(), insert(), query(), update(), getType(), and onCreate() methods. For example, overload its onCreate and query methods in the following example.

public class MyProvider extends ContentProvider {

 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public String getType(Uri uri) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public Uri insert(Uri uri, ContentValues values) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public boolean onCreate() {
  // Create a new database and insert a data  SQLiteDatabase db=().openOrCreateDatabase("test_db2.db", Context.MODE_PRIVATE, null);
  ("CREATE TABLE t_user (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)");
  ContentValues values=new ContentValues();
  ("name", "liangjh2");
  ("t_user", "id", values);
  ();
  return false;
 }

 @Override
 public Cursor query(Uri uri, String[] projection, String selection,
   String[] selectionArgs, String sortOrder) {
  // Get data  SQLiteDatabase db=().openOrCreateDatabase("test_db2.db", Context.MODE_PRIVATE, null);
  Cursor c = ("t_user", null, null, null, null, null, null);
  ();
  return c;
 }

 @Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs) {
  // TODO Auto-generated method stub
  return 0;
 }

}

Register ContentProvider
Declare ContentProvider in the Authorities property defines the Uri identity of ContentProvider. The Uri logo belongs to another category, please check it yourself. The provider logo should be placed in <application></application>. If you encounter an error "Permission Denial: opening provide...", you can try adding "android:exported="true"" to the node.

<application ...>
 ...
 <provider android:name=".MyProvider" android:authorities="" android:exported="true"/>
</application>

2) Obtain data in program B
Use Context to get the current ContentResolver, and obtain the data of program A based on the Uri address and the query method of ContentResolver. The Uri address and the autorities defined in the A program must be consistent. Of course, other operations can be performed in the same category.

Context ctx=;
ContentResolver resolver =();
Uri uri=("content://");
Cursor c = (uri, null, null, null, null);
();
while(!()){
 for(int i=0,j=();i<j;i++){
  ("Android2",""+(i));
 }
 ();
}

The above is all about this article, I hope it will be helpful to everyone's learning.