Android--SharePreference file storage (1)

1. Basic introduction

  • Belongs to a lightweight storage framework
  • Save as key-value
  • Save in the data/data/package name/shared_prefs directory
  • Data types that can be saved: booleans, floats, ints, longs, strings

Second, the steps

  • Get SharedPreferences object
  • Read data through SharedPreferences object
  • Store data through the SharedPreferences object
public class MainActivity extends AppCompatActivity {
    
    
    private String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //取值
        SharedPreferences settings = getSharedPreferences("login", 0);
        String username = settings.getString("username","");
        Long password = settings.getLong("password",0);
        float salary = settings.getFloat("salary",0f);
        Boolean sex = settings.getBoolean("sex",false);
        Log.i(TAG,"--------"+username);
        Log.i(TAG,"--------"+password);
        Log.i(TAG,"--------"+salary);
        Log.i(TAG,"--------"+sex);
    }

    @Override
    protected void onStop(){
    
    
        super.onStop();
        //写值
        Map<String,Object> map = new HashMap<>();
        map.put("username","zhangsan");
        map.put("password",123456l);
        map.put("salary",1234.34f);
        map.put("sex",false);
        //文件名不需要后缀名,默认xml
        savaSharedPreferences("login",map);
    }

    public Boolean savaSharedPreferences(String fileName, Map<String,Object> map){
    
    
    	//获取SharedPreferences对象
        SharedPreferences preferences = getSharedPreferences(fileName,Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = preferences.edit();
        for (Map.Entry<String,Object> entry:map.entrySet()){
    
    
            String key = entry.getKey();
            Object values = entry.getValue();
            if (values instanceof String){
    
    
                edit.putString(key,(String)values);
            } else if(values instanceof Boolean){
    
    
                edit.putBoolean(key,(Boolean)values);
            } else if(values instanceof Long){
    
    
                edit.putLong(key,(Long)values);
            } else if (values instanceof Float){
    
    
                edit.putFloat(key,(Float)values);
            }else if(values instanceof Integer){
    
    
                edit.putInt(key,(Integer)values);
            }
        }
        //提交
        boolean commit = edit.commit();
        return commit;
    }
}

The format of the saved file is as follows:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="password">1236</string>
    <boolean name="isRemember" value="true" />
    <boolean name="forget" value="false" />
    <string name="userName">张三</string>
</map>

Three, case

Case description : After we enter the user name and password, click Remember Password, then the account password will be displayed by default when we log in next time. If you don’t check Remember Password, you will need to enter it yourself next time you log in

The renderings are as follows: the

code is as follows:

<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">

    <EditText
        android:id="@+id/editTextuserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="用户名"
        android:inputType="text" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="密码"
        android:inputType="textPassword" />
    <CheckBox
            android:id="@+id/isRemember"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="记住密码" />
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录" />
    <Button
        android:id="@+id/btnRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="注册" />
</LinearLayout>
public class MainActivity extends PreferenceActivity {
    
    
    private String TAG = "MainActivity";
    private EditText edtUserName,edtPassWord;
    private Button btnLogin,btnRegister;
    private CheckBox isRemember;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();
        //获取文件数据
        Map<String, ?> map = getSharePreference();
        if (map != null && !map.isEmpty()){
    
    
            String userName = map.get("userName").toString().trim();
            String password = map.get("password").toString().trim();
            Boolean isBeRe = (Boolean) map.get("isRemember");
            Boolean isforget = (Boolean) map.get("forget");
            edtUserName.setText(userName);
            edtPassWord.setText(password);
            isRemember.setChecked(isBeRe);
        }
        //登录点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                Map<String,Object> map = new HashMap<>();
                //是否勾选记住密码
                if (isRemember.isChecked()){
    
    
                    map.put("userName",edtUserName.getText().toString());
                    map.put("password",edtPassWord.getText().toString());
                    map.put("isRemember",isRemember.isChecked());
                    savaSharePreference(map);
                }else{
    
    
                    map.put("userName","");
                    map.put("password","");
                    map.put("isRemember",isRemember.isChecked());
                    savaSharePreference(map);
                }
            }
        });
    }

    public void findView(){
    
    
        edtUserName = findViewById(R.id.editTextuserName);
        edtPassWord = findViewById(R.id.editTextPassword);
        btnLogin = findViewById(R.id.btnLogin);
        isRemember = findViewById(R.id.isRemember);
    }

    /**
     * 将数据保存到文件
     * @param map 数据内容
     * @return
     */
    public boolean savaSharePreference(Map<String,Object> map){
    
    
        //获取SharedPreferences对象
        SharedPreferences preferences = getSharedPreferences("login",MODE_PRIVATE);
        SharedPreferences.Editor edit = preferences.edit();
        for (Map.Entry<String,Object> entry:map.entrySet()){
    
    
            String key = entry.getKey();
            Object values = entry.getValue();
            if (values instanceof String){
    
    
                edit.putString(key,(String)values);
            } else if(values instanceof Boolean){
    
    
                edit.putBoolean(key,(Boolean)values);
            } else if(values instanceof Long){
    
    
                edit.putLong(key,(Long)values);
            } else if (values instanceof Float){
    
    
                edit.putFloat(key,(Float)values);
            }else if(values instanceof Integer){
    
    
                edit.putInt(key,(Integer)values);
            }
        }
        boolean flag = edit.commit();
        return flag;
    }

    /*
    获取文件内容
     */
    public Map<String, ?> getSharePreference(){
    
    
        SharedPreferences preferences = getSharedPreferences("login",MODE_PRIVATE);
        Map<String, ?> map = preferences.getAll();
        return map;
    }
}

Guess you like

Origin blog.csdn.net/weixin_55175040/article/details/115303282