SharedPreferences是Android平台上一个轻量级的存储类,当程序中有一些少量数据需要持久化存储时,可以使用SharedPreferences进行存储。
一、SharedPreferences的数据操作
1、将数据存入SharedPreferences中
使用SharedPreferences存储数据时,首先需要调用getSharedPreferences()方法获取SharedPreferences的实例对象。由于该对象本身只能获取数据,不能对数据进行存储和修改,所以需要调用SharedPreferences的edit()方法获取到可编辑的Editor对象,最后通过Editor对象的putXxx()方法存储数据,示例代码如下:
//获取sp对象,参数“data”表示文件名,MODE_PRIVATE表示文件操作模式
SharedPreferences sp=getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putString("name","张三");
editor.putInt("age",8);
editor.commit();
由上述代码可知,Editor对象是以键值对的形式保存数据的,value的值只能是Float、Int、Long、Boolean、String和Set<String>类型。同时,需注意,操作完数据后,一定要调用commit()方法进行数据提交,否则所有操作不生效。
2、读取SharedPreferences中的数据
读取SharedPreferences中的数据十分简单,只需要获取到SharedPreferences对象,然后通过该对象的getXxx()方法获取到相应的key即可,示例代码如下:
SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE)
String data = sp.getString("name","");//获取用户名
注意,getXxx()方法的第二个参数为缺省值,如果sp对象中不存在该key,则将返回缺省值,也就是说在上述例子中,如果“name”不存在,则会返回空字符串。
3、删除SharedPreferences中的数据
如果需要删除SharedPreferences中的数据,则只需要调用Editor对象的remove(String key)方法或者clear()方法即可,示例代码如下:
editor.remove("name");
editor.clear();
二、实战演练
在Android APP的登录界面中,当用户登录成功时,保存用户名和密码到Shared Preferences中。下一次显示登录界面时,将用户名密码读取到相应的输入框中,避免用户的再次输入。
1、程序源码
SPsave.java(工具类)
public class SPsave {
//保存账号密码到data.xml中
public static boolean saveUserInfo(Context context, String accout, String password){
SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor edit= sp.edit();
edit.putString("userName",accout);
edit.putString("pwd",password);
edit.commit();
return true;
}
//从data.xml文件中获取存储的QQ账号与密码
public static String[] getUserInfo(Context context){
SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
String account= sp.getString("userName",null);
String password= sp.getString("pwd",null);
String []userMap=new String[]{account,password};
return userMap;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btnLogin;
private EditText account;
private EditText password;
private TextView result;
String [] userInfo;
String sAccount;
String sPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
init();
}
//初始化函数
private void init(){
btnLogin=findViewById(R.id.button);
account=findViewById(R.id.editTextText);
password=findViewById(R.id.editTextTextPassword);
result=findViewById(R.id.tv_result);
//获取SP中的信息
userInfo=SPsave.getUserInfo(this);
//如果SP中有值,则填入SP中存储的值
if(userInfo[0]!=null){
account.setText(userInfo[0]);
password.setText(userInfo[1]);
}
//按钮绑定事件
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//获取文本框中的值
sAccount=account.getText().toString();
sPassword=password.getText().toString();
//判断账号、密码是否正确,不可用==判读
if(sAccount.equals("tom") && sPassword.equals("123")){
result.setText("登录成功!");
}else {
result.setText("账号或密码错误。。。");
}
//将输入的值存入SP
SPsave.saveUserInfo(MainActivity.this,sAccount,sPassword);
}
});
}
}
layout.xml(布局文件)
注意需要在res文件夹下创建drawable-hdpi文件夹存入对应的图片。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/loginbackground">
<TextView
android:text="登录"
android:textSize="20dp"
android:textColor="@color/white"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView3"/>
<TextView
android:text="<"
android:textSize="20dp"
android:textColor="@color/white"
android:layout_alignBottom="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView4"/>
<ImageView
android:layout_below="@+id/textView3"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/logintouxiang" android:id="@+id/imageView"/>
<EditText
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="用户名"
android:ems="15"
android:id="@+id/editTextText"/>
<ImageView
android:layout_toLeftOf="@+id/editTextText"
android:layout_alignTop="@+id/editTextText"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/loginaccount2" android:id="@+id/imageView2"/>
<EditText
android:layout_below="@+id/editTextText"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="密码"
android:ems="15"
android:id="@+id/editTextTextPassword"/>
<ImageView
android:layout_toLeftOf="@+id/editTextTextPassword"
android:layout_alignTop="@+id/editTextTextPassword"
android:layout_marginTop="5dp"
android:layout_marginRight="3dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/loginpassword" android:id="@+id/imageView3"/>
<TextView
android:text="□记住密码"
android:textColor="@color/white"
android:layout_below="@+id/editTextTextPassword"
android:layout_alignLeft="@id/editTextTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView"/>
<TextView
android:text="忘记密码?"
android:textColor="@color/red"
android:layout_below="@+id/editTextTextPassword"
android:layout_alignRight="@id/editTextTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView2"/>
<Button
android:text="登录"
android:backgroundTint="@color/blue"
android:layout_centerHorizontal="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="10dp"
android:layout_width="80dp"
android:layout_height="wrap_content" android:id="@+id/button"/>
<TextView
android:text="————其他登录方式————"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textColor="@color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView5"/>
<ImageView
android:layout_below="@+id/textView5"
android:layout_marginTop="8dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/loginqq" android:id="@+id/imageView4"/>
<ImageView
android:layout_below="@+id/textView5"
android:layout_marginTop="8dp"
android:layout_marginRight="10dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/loginwechat" android:id="@+id/imageView5"/>
<ImageView
android:layout_below="@+id/textView5"
android:layout_marginTop="8dp"
android:layout_marginRight="10dp"
android:layout_toRightOf="@id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/loginzhi" android:id="@+id/imageView6"/>
<TextView
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:textColor="@color/black"
android:background="@color/white"
android:layout_centerInParent="true"
android:id="@+id/tv_result"/>
</RelativeLayout>
2、运行结果
(第一次进入主页) (登录成功) (再次进入首页)