Shared Preferences: Data Storage and Access

Using Shared Preferences to save data, when our application wants to save some preference parameters of users, such as whether to log in automatically, whether to remember the account password, whether to connect to the Internet in Wifi, and other related information, it seems a bit overkill if we use the database! We call the above configuration information user preference settings, which is user preference settings, and these configuration information is usually stored in a specific file! For example, windows uses ini files, while J2SE uses properties files and xml files to save configuration information of software; in Android, we usually use a lightweight storage class, Shared Preferences, to save preferences of users! Shared Preferences also uses xml files, which are similar to Map collections and store data in the form of key-value; we only need to call getXxx(name) of Shared Preferences to get the corresponding value according to the key! It's very convenient to use!

 

Shared Preferences is a lightweight Android data storage method. Its essence is to store key-value pairs of data based on XML files. It is usually used to store some simple configuration information. Its storage location is in the / data / data /< package name > / shared_prefs directory. SharedPreferences object itself can only obtain data without supporting storage and modification. Storage modification is implemented through Editor object. Classic usage, such as user input box for storing past login accounts. The steps to implement Shared Preferences storage are as follows:

 

1. Get SharedPreferences objects from Context
2. Use edit() method to get Editor object.
3. Store key-value key-value pairs of data through Editor objects.
4. Submit data through apply().

Copyright Statement: This article is the original article of the blogger. Please attach a link to the origin of the original article and this statement for reproducing. 2019-08-28, 17:41:40.
By - - - Drowning and Floating - - - Blog Garden

Use of Shared Preferences

SharedPreferences object itself can only obtain data without supporting storage and modification. Storage modification is achieved through the internal interface Editor object acquired by SharedPreferences.edit(). Preference is used to access data, Shared Preferences interface and Shared Preferences internal interface Shared Preferences. Editor are used in the android.content package.

 1 1)Write data:
 2      //Step 1: Create a SharedPreferences object
 3      SharedPreferences sharedPreferences= getSharedPreferences("data",Context.MODE_PRIVATE);
 4      //Step 2: Instance SharedPreferences.Editor object
 5      SharedPreferences.Editor editor = sharedPreferences.edit();
 6      //Step 3: Put the captured values into the file
 7      editor.putString("name", "Tom");
 8      editor.putInt("age", 28);
 9      editor.putBoolean("marrid",false);
10      //Step 4: Submit               
11      editor.commit();(apply())
12 
13  2)Read data:
14      SharedPreferences sharedPreferences= getSharedPreferences("data", Context .MODE_PRIVATE);
15      String userId=sharedPreferences.getString("name","");
16   
17 3)Delete specified data
18      editor.remove("name");
19      editor.commit();
20 
21 4)wipe data
22      editor.clear();
23      editor.commit();(apply())

 

Copyright Statement: This article is the original article of the blogger. Please attach a link to the origin of the original article and this statement for reproducing. 2019-08-28, 17:41:40.
Author By - - - Drowning and Floating - - - Blog Garden

 

Note: If you use Shared Preferences in Fragment, you need to initialize Shared Preferences in onAttach(Activity activity), otherwise the null pointer, getActivity(), will probably return null!

The Shared Preferences steps for reading and writing other applications are as follows (not practiced):
When creating Shared Preferences, specify MODE_WORLD_READABLE mode, which indicates that the Shared Preferences data can be read by other programs.
_2. Create Context corresponding to other applications;
_3. Use the Context of other programs to get the corresponding Shared Preferences;
4. If the data is written, use the Editor interface. All other operations are consistent with the previous ones.

 1* Four modes of operation for Shared Preferences data:
 2*1. Context.MODE_PRIVATE
 3*2. Context.MODE_APPEND
 4*3. Context.MODE_WORLD_READABLE
 5*4. Context.MODE_WORLD_WRITEABLE
 6      *
 7 * Context. MODE_PRIVATE: The default mode of operation means that the file is private data and can only be accessed by the application itself. In this mode, the contents written will overwrite the contents of the original file.
 8 * Context. MODE_APPEND: The schema checks whether a file exists and adds content to the file if it exists, otherwise a new file is created.
 9 * Context. MODE_WORLD_READABLE and Context.MODE_WORLD_WRITEABLE are used to control whether other applications have permission to read and write the file.
10      *
11 * MODE_WORLD_READABLE: Indicates that the current file can be read by other applications.
12 * MODE_WORLD_WRITEABLE: Indicates that the current file can be written by other applications
13      *
14 * Special note: For security reasons, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE have been discarded in Android 4.2

 

 1 try {
 2 //There com.example.mpreferences Is the package name of the application
 3  Context mcontext = createPackageContext("com.example.mpreferences", CONTEXT_IGNORE_SECURITY);
 4 
 5  SharedPreferences msharedpreferences = mcontext.getSharedPreferences("name_preference", MODE_PRIVATE);
 6  int count = msharedpreferences.getInt("count", 0);
 7 
 8  } catch (PackageManager.NameNotFoundException e) {
 9        e.printStackTrace();
10  }

 

 

Create a new Android project and add code to res, layout, activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="User login"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="enter one user name"/>
    <EditText
            android:id="@+id/editUserName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="User name"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Please input a password"/>
    <EditText
            android:id="@+id/editUserPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"/>
    <Button
            android:id="@+id/button_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Land"/>
</LinearLayout>

The results are as follows:

 

Simple SharedPreferences tool class to write SharedPreferences.java

 1 package com.Reverse-xiaoyu.sharedpreferencesutillty;
 2 
 3 import android.content.Context;
 4 import android.content.SharedPreferences;
 5 import android.widget.Toast;
 6 
 7 import java.util.HashMap;
 8 import java.util.Map;
 9 
10 public class SharedHelp {
11     private Context context;
12 
13     public SharedHelp(){
14 
15     }
16 
17     public SharedHelp(Context context){
18         this.context = context;
19     }
20 
21     public void save(String userName, String passWord){
22         SharedPreferences sp = context.getSharedPreferences("MyMap", Context.MODE_PRIVATE);
23         SharedPreferences.Editor editor = sp.edit();
24         editor.putString("userName", userName);
25         editor.putString("passWord", passWord);
26         editor.apply();
27         Toast.makeText(context, "Information has been written SharedPreferences in", Toast.LENGTH_SHORT).show();
28     }
29 
30     public Map<String, String> read(){
31         Map<String, String> data = new HashMap<String, String>();
32         SharedPreferences sp = context.getSharedPreferences("MyMap", Context.MODE_PRIVATE);
33         data.put("userName", sp.getString("userName", ""));
34         data.put("passWord", sp.getString("passWord", ""));
35         return data;
36     }
37 }

 

Implementing logic in MainActivity

 1 package com.Reverse-xiaoyu.sharedpreferencesutillty;
 2 
 3 import androidx.appcompat.app.AppCompatActivity;
 4 
 5 import android.content.Context;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 import android.widget.Button;
 9 import android.widget.EditText;
10 
11 import java.util.Map;
12 
13 public class MainActivity extends AppCompatActivity {
14     //instantiation layout in EditText Of editUserNmae
15     private EditText editUserName;
16     //instantiation layout in EditText Of editUserPassword
17     private EditText editUserPassword;
18     //instantiation layout in Button Of button_login
19     private Button button_login;
20     //Definition context
21     private Context context;
22     //Definition ShareHelp Objects of classes
23     private SharedHelp sharedHelp;
24     //Define two string names
25     private String strName;
26     private String strPassword;
27 
28     @Override
29     protected void onCreate(Bundle savedInstanceState) {
30         super.onCreate(savedInstanceState);
31         setContentView(R.layout.activity_main);
32         //Get context
33         context = getApplicationContext();
34         sharedHelp = new SharedHelp();
35         bindViews();
36     }
37 
38     private void bindViews(){
39         //Instantiated variable bindings correspond ID
40         editUserName = findViewById(R.id.editUserName);
41         editUserPassword = findViewById(R.id.editUserPassword);
42         button_login = findViewById(R.id.button_login);
43         //Setting listen events for buttons
44         button_login.setOnClickListener(new View.OnClickListener() {
45             @Override
46             public void onClick(View view) {
47                 //When a button is pressed to trigger, it is removed from the control getText()And convert it into a string
48                 strName = editUserName.getText().toString();
49                 strPassword = editUserPassword.getText().toString();
50                 //adopt SharedHelp In class save Method, save it
51                 sharedHelp.save(strName, strPassword);
52             }
53         });
54     }
55 
56     @Override
57     protected void onStart() {
58         super.onStart();
59         //Define a Map<String, String>Variables of type data Used to receive shareHelp.read()Method return value
60         Map<String, String> data = sharedHelp.read();
61         //Place the acquired data in two EditText in
62         editUserName.setText(data.get("userName"));
63         editUserPassword.setText(data.get("passWord"));
64     }
65 }

 

I don't recommend that the code be written at the entrance of the main program. I suggest writing another file to facilitate communication. I wrote it in MainActivity.

Copyright Statement: This is the original article of the blogger. Please attach the link of origin and this statement to reproduce it. 2019-08-28, 17:41:40.
By - - - Drowning and Floating - - - Blog Garden

 

Finally, write a tool set class for Shared Preferences

 SharedPreferencesUtillty.java

  1 package com.Reverse-xiaoyu.sharedpreferencesutillty;
  2 
  3 import android.content.Context;
  4 import android.content.SharedPreferences;
  5 
  6 import java.util.Map;
  7 
  8 public class SharedPreferenceUtillty {
  9     //Preserved SP file name
 10     public static final String FILE_NAME = "MyMap";
 11 
 12     /**
 13      * SharedPreferences Four modes of data manipulation:
 14      * I. Context.MODE_PRIVATE
 15      * II. Context.MODE_APPEND
 16      * Context.MODE_WORLD_READABLE
 17      * IV. Context.MODE_WORLD_WRITEABLE
 18      *
 19      * Context.MODE_PRIVATE: For the default mode of operation, the file represents private data and can only be accessed by the application itself. In this mode, the content written will overwrite the content of the original file.
 20      * Context.MODE_APPEND: The mode checks whether the file exists, adds content to the file if it exists, or creates a new file.
 21      * Context.MODE_WORLD_READABLE It is used with Context.MODE_WORLD_WRITEABLE to control whether other applications have permission to read and write the file.
 22      *
 23      * MODE_WORLD_READABLE: Represents that the current file can be read by other applications.
 24      * MODE_WORLD_WRITEABLE: Represents that the current file can be written by other applications
 25      *
 26      * Special note: For security reasons, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE have been discarded in Android version 4.2
 27      */
 28 
 29     /**
 30      * Save data
 31      */
 32     public static void putData(Context context, String key, Object object){
 33         //instantiation SharedPreferences Object (first step)
 34         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
 35         //instantiation SharedPreferences.Editor Object (Step 2)
 36         SharedPreferences.Editor editor = sp.edit();
 37         //use putObject The way you save data depends on the third parameter, which type of variable you use.
 38         if (object instanceof Boolean){
 39             editor.putBoolean(key, (Boolean) object);
 40         }else if (object instanceof Float){
 41             editor.putFloat(key, (Float) object);
 42         }else if (object instanceof Integer){
 43             editor.putInt(key, (Integer) object);
 44         }else if (object instanceof Long){
 45             editor.putLong(key, (Long) object);
 46         }else if (object instanceof String){
 47             editor.putString(key, (String) object);
 48         }
 49         editor.apply();
 50     }
 51 
 52     /**
 53      * Get the specified data
 54      */
 55     public static Object getData(Context context, String key, Object object){
 56         //instantiation SharedPreferences Object (first step)
 57         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
 58         //use getObject The way you save data depends on the third parameter, which type of variable you use.(Step 2)
 59         if (object instanceof Boolean){
 60             return sp.getBoolean(key, (Boolean) object);
 61         }else if (object instanceof Float){
 62             return sp.getFloat(key, (Float) object);
 63         }else if (object instanceof Integer){
 64             return sp.getInt(key, (Integer) object);
 65         }else if (object instanceof Long){
 66             return sp.getLong(key, (Long) object);
 67         }else if (object instanceof String){
 68             return sp.getString(key, (String) object);
 69         }
 70         return null;
 71     }
 72 
 73     /**
 74      * Returns all key-value pairs
 75      */
 76     public static Map<String, ?> getAll(Context context){
 77         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
 78         Map<String, ?> map = sp.getAll();
 79         return map;
 80     }
 81 
 82     /**
 83      * Check whether the corresponding data exists
 84      */
 85     public static boolean contains(Context context, String key){
 86         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
 87         return sp.contains(key);
 88     }
 89 
 90     /**
 91      * Delete data with a specified key value
 92      */
 93     public static void remove(Context context, String key){
 94         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
 95         SharedPreferences.Editor editor = sp.edit();
 96         editor.remove(key);
 97         editor.apply();
 98     }
 99 
100     /**
101      * Delete all data
102      */
103     public static void clear(Context context, String key){
104         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
105         SharedPreferences.Editor editor = sp.edit();
106         editor.clear();
107         editor.apply();
108     }
109 
110 }

 

Copyright Statement: This article is the original article of the blogger. Please attach a link to the origin of the original article and this statement for reproducing. 2019-08-28, 17:41:40.
By - - - Drowning and Floating - - - Blog Garden

Tags: Android Java xml Database

Posted on Wed, 28 Aug 2019 03:54:26 -0700 by xxtobirichter