• 欢迎光临~

Android---SharePreference文件储存(一)

开发技术 开发技术 2021-03-30 87次浏览

一、基本介绍

  • 属于一个轻量级的存储框架
  • 以key-value形式保存
  • 保存在data/data/package name/shared_prefs目录下
  • 可以保存的数据类型:booleans, floats, ints, longs,strings

二、步骤

  • 获取SharedPreferences对象
  • 通过SharedPreferences对象读取数据
  • 通过SharedPreferences对象存储数据
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;
    }
}

保存的文件格式如下:

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

三、案例

案例描述:当我们输入用户名和密码后,点击记住密码,那我们下次登录时账号密码就会默认显示,不勾选记住密码则下次登录则需要自己输入

效果图如下:
Android---SharePreference文件储存(一)
代码如下:

<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;
    }
}
程序员灯塔
转载请注明原文链接:Android---SharePreference文件储存(一)
喜欢 (0)