SharedPreferences是Android中的一个轻量级的存储类,用于存储少量配置信息,例如:本地的用户名和密码、是否开启震动等。从数据存储来讲,手机毕竟是一个终端设备,不适合存储大量数据,尽量在本地存储少量信息为开发原则。
第1步:布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入key"/>
<EditText
android:id="@+id/value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入value"/>
<Button
android:id="@+id/writeBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="存入SharedPreferences"/>
<Button
android:id="@+id/readBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取SharedPreferences"/>
</LinearLayout>
用户输入的key和value作为存入SharedPreferences里面的键值对,写入的时候,按照键值对方式存入,读取的时候,把存储的所有的键值对都读取出来。
第2步:逻辑文件
package com.yibinu.sharedpreferencesdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText key;
EditText value;
Button writeBtn;
Button readBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
key = findViewById(R.id.key);
value = findViewById(R.id.value);
writeBtn = findViewById(R.id.writeBtn);
readBtn = findViewById(R.id.readBtn);
writeBtn.setOnClickListener(this);
readBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id==R.id.writeBtn){
SharedPreferences yimi = getSharedPreferences("yimi", MODE_PRIVATE);
SharedPreferences.Editor edit = yimi.edit();
edit.putString(key.getText().toString(),key.getText().toString());
edit.putString(key.getText().toString(),value.getText().toString());
edit.apply();
} else if (id==R.id.readBtn) {
SharedPreferences yimi = getSharedPreferences("yimi", MODE_PRIVATE);
Map<String, ?> all = yimi.getAll();
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, ?> entry :all.entrySet()) {
String key1 = entry.getKey();
String value1 = (String) entry.getValue();
sb.append(key1+","+value1);
}
Toast.makeText(this, ""+sb.toString(), Toast.LENGTH_SHORT).show();
}
}
}
核心思想,通过getSharedPreferences方法获取SharedPreferences接口,通过其edit方法获取到编辑对象,才能实现编辑存储的键值对。获取的时候需要先获得getSharedPreferences对象,再调用其各种方法,获得存入的键值对。
第3步:测试
SharedPreferences效果