天天看点

SharedPreferences保存用户名、密码的简单使用

1.什么是SharedPreferences 存储?

SharedPreferences是Android平台上一个轻量级的存储类,用来存储少量数据时简单,便捷(保存记住密码状态,设置开关状态等)。

以key-value(键值对)形式存储数据,可以存储的数据类型为:String、float、int、long、boolean。

存储位置在/data/data/<包名>/shared_prefs目录下。 保存的数据以XML形式存储。

2.使用SharedPreferences写入数据步骤:

1.获得使用SharedPreferences对象;

2.获得Editor对象;

3.通过Editor对象的putXXX函数,设置写入数据;

4.通过Editor对象的commit提交写入;

btn_back.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        //1 创建 SharePreferences 对象
        String username = edit_name.getText().toString();
        String password = edit_password.getText().toString();
        SharedPreferences sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);

        //2  创建Editor对象,3 写入值
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("name", username);
        editor.putString("password",password);

        //4  提交
        editor.commit();
        Toast.makeText(MainActivity.this, "提交成功", Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(MainActivity.this,Main2Activity.class);
        intent.putExtra("username","用户名为"+username);
        startActivity(intent);
        finish();
    }
});
           

3.使用sharedPreferences.getString方法读取数据:

if (sharedPreferences != null) {
// 读取数据,用sharedPreferences.getString方法
    String name = sharedPreferences.getString("name", "");
    String password = sharedPreferences.getString("password", "");
    edit_name.setText(name);
}
           

4.将EditText框中写入的数据传送到其他页面:

MainActivity:
    String username = edit_name.getText().toString();
    Intent intent = new Intent(MainActivity.this,Main2Activity.class);
    intent.putExtra("username","用户名为"+username);
    startActivity(intent);
    finish();
    
Main2Activity:
    textView.setText(intent.getStringExtra("username"));