SharedPreferences是什么
SharedPreferences是一个轻量级的存储类,用来存储少量数据时简单、便捷。
以key_value形式存储数据,可以存储数据类型为:String、float、int、long、boolean。
使用SharedPreferences写入数据步骤
- 获得SharedPreferences对象;
- 获得Editor;
- 通过Editor对象的putXXX函数,设置写入数据;
- 通过Editor对象的commit提交。
获得SharedPreferences对象
getSharedPreferences 方法的参数:
- name:要保存的文件名;
- mode:MOOE_PRIVATE:写入的文件会覆盖原文件内容;MOOE_APPEND:检查文件是否存在,存在就追加内容,不存在就创建新的文件。
Editor
通过SharedPreferences.edit方法获得,Editor对象代表数据编辑对象,通过此对象可以写入数据。
Editor对象的 commit方法:
提交数据。
从SharedPreferences中取值
- 获得SharedPreferences对象;
- getXXX函数复制
代码演示:
登录时点击记住密码,下次登录便不用输入密码。
xml布局文件:
<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:hint="请输入账号"
android:id="@+id/zhanghao"/>
<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/mima"
android:inputType="textPassword"
android:hint="请输入密码"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="记住密码"
/>
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:textSize="20sp"
android:id="@+id/denglubtn"
android:layout_toRightOf="@+id/checkBox"
/>
Activity代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText zhanghao;
private EditText mima;
private Button btn;
private CheckBox checkBox;
private int rememberFlag=0;//标志位,标志CheckBox,是否为记住密码
private String password="";//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindID();
//从sp文件中取出name结点对应的值
SharedPreferences sharedPreferences=getSharedPreferences("zhanghao.xml",MODE_PRIVATE);
if(sharedPreferences!=null){
String name=sharedPreferences.getString("name","");
password=sharedPreferences.getString("password","");
rememberFlag=sharedPreferences.getInt("remember_flag",0);
//赋值给username
zhanghao.setText(name);
}
if(rememberFlag==1){
//
checkBox.setChecked(true);
mima.setText(password);
}
}
private void bindID() {
zhanghao=findViewById(R.id.zhanghao);
mima=findViewById(R.id.mima);
btn=findViewById(R.id.denglubtn);
checkBox=findViewById(R.id.checkBox);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String username =zhanghao.getText().toString();
String password =mima.getText().toString();
//创建SharePreferences对象
SharedPreferences sp=getSharedPreferences("zhanghao.xml",MODE_PRIVATE);
//创建Ediyor对象
SharedPreferences.Editor editor=sp.edit();
//写入Editor对象的值
editor.putString("name",username);
if (checkBox.isChecked()){
//记住密码
rememberFlag=1;
editor.putInt("remember_flag",rememberFlag);//写入标志位,用来判断是否记住密码
editor.putString("password",password);//输入密码
}else {
//没记住密码
rememberFlag=0;
editor.putInt("remember_flag",rememberFlag);
}
//提交
editor.commit();
Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
}
}