解析
什么是Shared Perferences
应用场景
- 配置信息
- 主题信息
- 游戏的积分信息等
存储路径
在本应用中的data-data-应用包-自定义名称xml文件下保存写入的数据信息
使用
获取步骤
读取步骤
实例
代码
1、需求:实现自动登录,例如qq的可以设置自动登录,然后下一次就不用再写登录账号密码
2、activity_main.xml:简易实现输入框
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="账号"
></EditText>
<EditText
android:id="@+id/pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword"
></EditText>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="登录"
></Button>
</LinearLayout>
3、MainActivit.java
package com.example.sharedperference_page;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// 测试使用的账号密码
private String mu = "123";
private String mp = "123";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 第一个参数是保存信息的文件名,文件名不需要手动创建
* 第二个参数表示文件为只能本应用读写
*/
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
// 获取存储文件中的账号密码
String username = sharedPreferences.getString("account", null);
String password = sharedPreferences.getString("pwd", null);
if(username != null && password != null){
// 获取值不为空那么进行比较,比较成功进行登录
if(username.equals(mu) && password.equals(mp)){
Toast.makeText(MainActivity.this, "自动登录成功"+username+password, Toast.LENGTH_SHORT).show();
}
}else{
// 存储文件出现字段缺失就监听登录事件进行存储
Button button = findViewById(R.id.login);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText username_editText = findViewById(R.id.account);
EditText pwd_editText = findViewById(R.id.pwd);
String u = username_editText.getText().toString();
String p = pwd_editText.getText().toString();
if(u.equals(mu) && p.equals(mp)){
// 创建editor对象
SharedPreferences.Editor editor = sharedPreferences.edit();
// 写入数据
editor.putString("account", mu);
editor.putString("pwd", mp);
// 提交保存
editor.commit();
Toast.makeText(MainActivity.this, "账号密码保存成功", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "账号或密码保存错误", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
文件查看
使用Android Studio