SharePreference是android的一种轻量级的数据存储工具。
一般用于保存短信、用户账号资料、联系人等。
其以键值对的方式存储程序的应用信息。
其只能存储基本的数据类型:boolean、float、int、long、String。
其以XML文件的形式保存在/data/data/程序包名/shard_prefs。
其基本使用很简单,效果图如下:
主要用到的类:SharePreferences、Eitor、Map(遍历全部数据时用)
1.声明并实例化SharePreferences,用到静态方法getSharePreferences(name,mode)
(1)、name:表示数据存储位置的文件名,不用带后缀
(2)、mode:文件查看的权限
MODE_PRIVATE:默认操作模式,表示该文件私有,只能被应用本身访问。(这里我们用默认模式)
2.声明并实例化Editor,用到SharedPreferences的edit()方法。
3.之后便可以用Editor的对象执行增、删、改、查
(1)增加数据:putString(“key”,“value”);仅支持存储基本的数据类型,增加数据之后调用commit();方法上交,否则操作无效
(2)删除数据:调用remove(“key”);方法,之后还要调用commit方法上交
(3)修改数据:就是对键值相同的数据的覆盖
(4)查找数据:调用SharedPreferences的getString方法(仅支持存储基本的数据类型)第一个参数为key,第二个参数为""(空)
4.遍历所有数据则要调用SharedPreferences的getAll()方法,其返回的时一个Map,遍历Map即可
java代码:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Map;
public class MainActivity extends Activity {
public TextView show;
public EditText edit;
public Button sure;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Map<String,String> map ;
@SuppressLint("CommitPrefEdits")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
edit = findViewById(R.id.edit);
sure = findViewById(R.id.sure);
//1.实例化SharedPreferences,第一个参数是文件名字,第二个参数是模式
sharedPreferences = getSharedPreferences("test",MODE_PRIVATE);
//2.实例化Editor
editor = sharedPreferences.edit();
sure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//1.装入数据
editor.putString("name",edit.getText().toString());
//2.上交数据
editor.commit();
//3.浏览数据
show.setText(sharedPreferences.getString("name",""));
//4.浏览全部数据
Map<String,?> map = sharedPreferences.getAll();
for(Map.Entry k : map.entrySet()){
Log.i("Key"+k.getKey(),"Value"+sharedPreferences.getString(k.getKey().toString(),""));
}
//5.删除数据
editor.remove("name").commit();
}
});
}
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.sharedprefences.MainActivity">
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/sure"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="写入"
/>
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>