GitHub项目地址:
https://github.com/Skymqq/SharedPreferencesSave.git
不同于文件的存储方式,SharedPreferences是使用键值对的方式来存储数据的。也就是说,当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在读取数据的时候就可以通过这个键把相应的值取出来。而且SharePreferences还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的;如果存储的数据是一个字符串,那么读取出来的数据仍然是字符串。
这样你应该就能很明显地感觉到,使用SharedPreferences来进行数据持久化要比使用文件更方便很多,下面我们就来看一下它的具体用法。
要想使用SharedPreferences来存储数据,首先需要获取到SharedPreferences对象。Android中主要提供了3中方法用于得到SharedPreferences对象。
1.Context类中的getSharedPreferences()方法
此方法接收两个参数,第一个参数用于指定SharedPreferences文件的名称,如果指定的文件不存在则会自动创建一个,SharedPreferences文件都是存放在data/data/<package name>/shared_prefs/目录下的。第二个参数用于指定操作模式,目前只有MODE_PRIVATE这一种模式可以选择,它是默认的操作模式,和直接传入0的效果是相同的,表示只有当前的应用程序才可以对这个SharedPreferences文件进行读写。其他几种操作模式均已被废弃,MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE这两种模式是在Android4.2版本中被废弃的,MODE_MULTI_PROCESS模式是在Android6.0版本中被废弃的。
2.Activity类中的getPreferences()方法
这个方法和Context中的getSharedPreferences()方法很相似,不过它只接收一个操作模式参数,因为使用这个方法时会自动将当前活动的类名作为SharedPreferences的文件名。
3.PreferenceManager类中的getDefaultSharedPreferences()方法
这是一个静态方法,它接收一个Context参数,并自动使用当前应用程序的包名作为前缀来命名SharedPreferences文件。得到了SharedPreferences对象之后,就可以开始向SharedPreferences文件中存储数据了,主要可以分未步来实现。
(1)调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象。
(2)向SharedPreferences.Editor对象中添加数据,比如添加一个布尔型数据就使用putBoolean()方法,添加一个字符串则使用putString()方法,以此类推。
下面我们新建一个SharedPreferencesSave项目,然后在activity_main.xml中添加一个Button控件。
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">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SPSave"
android:textAllCaps="false"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
MainActivity.java代码:
package com.example.administrator.sharedpreferencessave;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btn = (Button) findViewById(R.id.btn);
}
@Override
protected void onResume() {
super.onResume();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
Toast.makeText(MainActivity.this, "data already saved in sp", Toast.LENGTH_SHORT).show();
}
});
}
private void save() {
SharedPreferences.Editor editor = this.getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("name", "Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
editor.apply();
}
}
可以看到,这里首先给按钮注册了一个点击事件,然后在点击事件中通过getSharedPreferences()方法指定SharedPreferences文件名为data,并得到了SharedPreferences.Editor对象。接着向这个对象中添加了3条不同类型的数据,最后调用apply()方法进行提交,从而完成了数据存储的操作。
运行程序,点击Button按钮,效果图如下所示:
在Device File Explorer中找到data.xml文件,打开如下所示:
从SharedPreferences中读取数据
修改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">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SPSave"
android:textAllCaps="false"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/btn_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SPRead"
android:textAllCaps="false"
android:textSize="20sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name: "
android:textAllCaps="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="name"
android:textAllCaps="false"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="age: "
android:textAllCaps="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="age"
android:textAllCaps="false"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="married: "
android:textAllCaps="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_married"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="married"
android:textAllCaps="false"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
MainActivity.java代码:
package com.example.administrator.sharedpreferencessave;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn, btn_read;
private TextView tv_name, tv_age, tv_married;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btn = (Button) findViewById(R.id.btn);
btn_read = (Button) findViewById(R.id.btn_read);
tv_name = (TextView) findViewById(R.id.tv_name);
tv_age = (TextView) findViewById(R.id.tv_age);
tv_married = (TextView) findViewById(R.id.tv_married);
}
@Override
protected void onResume() {
super.onResume();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();//将数据保存入本地sp
Toast.makeText(MainActivity.this, "data already saved in sp", Toast.LENGTH_SHORT).show();
}
});
btn_read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
read();//将数据从本地sp中读取出来并显示
}
});
}
private void save() {
SharedPreferences.Editor editor = this.getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("name", "Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
editor.apply();
}
private void read() {
runOnUiThread(new Runnable() {
@Override
public void run() {
SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
String name = sp.getString("name", "");
int age = sp.getInt("age", 0);
boolean married = sp.getBoolean("married", false);
tv_name.setText("" + name);
tv_age.setText("" + age);
tv_married.setText("" + married);
Toast.makeText(MainActivity.this, "data already read in sp", Toast.LENGTH_SHORT).show();
}
});
}
}
效果图:
点击SPRead按钮,读取本地SP中的数据,并更新UI显示: