Android 数据存储——SharedPreferences 存储

SharedPreferences 是使用键值对的方式存储数据,是Android平台上用于存储如配置信息等轻量级存储数据的接口。为每一条数据提供一个对应的键,在读取数据时通过键把相应的值取出来。支持多种数据类型存储,存储方便简单

代码

Activity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class DataStorage_sp_Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datastorage_sp_activity);
}

public void onClick(View view){
EditText editText =(EditText) findViewById(R.id.editText);
String text = editText.getText().toString();
/* SharedPreferences存储
* 1.调用SharedPreferences对象的edit()方法,获取SharedPreferences.Editor对象
* 2.向SharedPreferences.Editor对象中添加数据,put方法(包括基本数据类型与String)
* 3.调用apply()或commit()方法将添加数据提交到“test”中
* */
SharedPreferences.Editor editor = getSharedPreferences("test",MODE_PRIVATE).edit();
editor.putString("name",text);
// editor.apply();
editor.commit();

/* SharedPreferences读取
* 1.定义SharedPreferences对象
* 2.从SharedPreferences对象中读取数据,get方法
* */
SharedPreferences sp = getSharedPreferences("test",MODE_PRIVATE);
String name = sp.getString("name","");
TextView textView =(TextView) findViewById(R.id.textView);
textView.setText(name);
}
}
layout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName" />

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="确定" />
</LinearLayout>