Android development, on the implementation of SharedPreferences persistent storage objects

Androd provides three methods for persistent storage of data, namely file storage, SharedPreferences storage, and database storage.

1. File storage is realized by combining openfileoutput() and openfileinput with Java stream, which is convenient and fast, and is saved locally in the form of files. However, text files can only store data of a single type of String, which is not suitable for other types.
2. Database storage, through the server's access to the database, the data storage becomes safe, stable and durable, and the core data can be obtained through the network at any time. However, data storage requires operations such as building a database, building a table, and implementing SQL statements, which are relatively troublesome and suitable for storing complex and important and shared data. However, a large number of open source frameworks make up for this shortcoming.
3. SharedPreferences obtains the sharedPreferences object, instantiates the editor, and saves data in the form of key-value pairs through editor.putint(key,data), editor.putString(key,Value), etc. Read data in sp.get(key) mode. The specific method is as follows:

//建立sp的编辑器, 第一个参数是自定义文件名,第二个参数默认
 SharedPreferences.Editor editor = getSharedPreferences(
                ConstantString.sharePreferencesName,MODE_PRIVATE).edit();
 String str = "lallalallallallal";
 editor.putString(key, str);
 editor.apply();  

Read data from the sharedPreferences object

//获得指定SP名文件的sharedpeferences对象
 SharedPreferences sp = getSharedPreferences(
 ConstantString.sharePreferencesName,MODE_PRIVATE);
 String getgson = sp.getString(
 key,"failtoGetDataValue");

Is it very simple? Next, implement the data storage implementation for the object type.
. . . . . .
. . . . .
. . . .
. . .
. .
.
I’m sorry to inform you that sharepreference does not provide storage for object type data, but don’t worry, we can convert the object type data into character storage, and then parse the character into an object to solve this problem perfectly. what is that?
That's right, it is json.
We store the object in json form, and then parse the stored json into an object to achieve the goal.
The specific operation is as follows:
First, we create a FirstActivity, and related xml,
it has only one function, which is to jump to the second SecondActivity; so I will not write the code of FirstActivity.

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EighthActivity">
    <EditText
        android:id="@+id/usename"
        android:hint="账号"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/password"
        android:hint="密码"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/recover_data"
        android:text="数据复现"
        android:onClick="recoverDataBySP"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Insert picture description here
When we enter the account and password, press the return button to return to FirstActivity, then the SecondActivity will be destroyed and the data will be recycled. At this time, start SecondActivity again in FirstActivity, the account password is naturally empty, click the data reproduction button to realize the account The function of refilling the password. This can be used to "remember app login account password, app login once and log in the next time you log in automatically without password input".
SecondActivity.java

public class SecondActivity extends BaseActivity {
    
    
     private EditText usename,password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        init();
    }
    public void init(){
    
    
        usename = (EditText)findViewById(R.id.usename);
        password = (EditText)findViewById(R.id.password);

    }
    //建立数据保存方法
    public void save(UserBean userBean){
    
    
        //建立sp的编辑器, 第一个参数是自定义文件名,第二个参数默认
        SharedPreferences.Editor editor = getSharedPreferences(
                ConstantString.sharePreferencesName,MODE_PRIVATE).edit();
        //把对象转化为gson,因为share preferences没有提供存储对象的方法,所以要转化gson
        Gson gson = new Gson();
        String changeObjecttoGson = gson.toJson(userBean);
        editor.putString(ConstantString.userBean,changeObjecttoGson);//key
        editor.apply();
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        String getusename = usename.getText().toString();
        String getpassword = password.getText().toString();
        UserBean userBean = new UserBean(getusename,getpassword);
        save(userBean);
    }

    //恢复数据,将gson转化回 user Bean对象
    public void recoverDataBySP(View view){
    
    
        switch (view.getId()){
    
    
            case R.id.recover_data:
                //获得指定SP名文件的sharedpeferences对象
                SharedPreferences sp = getSharedPreferences(ConstantString.sharePreferencesName,MODE_PRIVATE);
                //获得json
                String getgson = sp.getString(ConstantString.userBean,"failureGetJson");
                //将json转化为指定对象
                Gson gson = new Gson();
                Type type = new TypeToken<UserBean>(){
    
    }.getType();//获得UserBean对象类型
                UserBean userBean = gson.fromJson(getgson,type);
                usename.setText(userBean.getUsename());
                password.setText(userBean.getPassword());
            default:
                break;
        }
    }
}

UserBean.java

public class UserBean implements Serializable {
    
    
    private String usename;
    private String password;
    public UserBean(String c_usename,String c_password){
    
    
        this.usename = c_usename;
        this.password = c_password;
    }

    //Ctrl + Shift T  打开 try   catch  finally


    // Alt +  Ins
    public String getUsename() {
    
    
        return usename;
    }

    public void setUsename(String usename) {
    
    
        this.usename = usename;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

Guess you like

Origin blog.csdn.net/qq_41904106/article/details/108820182