sp存储专门用来存储一些单一的小数据
存储数据的类型 boolean float int long String
数据保存的路径/data/data/xxx(packageName)/shared_prefs/xxx.xml
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">
<EditText
android:id="@+id/et_sp_key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="存储的KEY" />
<EditText
android:id="@+id/et_sp_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="存储的VALUE" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="save"
android:text="保存" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="read"
android:text="读取" />
</LinearLayout>
</LinearLayout>
activity中的代码
package com.servicedemo.datastorage;
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.EditText;
import android.widget.Toast;
public class Spactivity extends AppCompatActivity {
private EditText et_sp_key;
private EditText et_sp_value;
private SharedPreferences.Editor edit;
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spactivity);
et_sp_key = findViewById(R.id.et_sp_key);
et_sp_value = findViewById(R.id.et_sp_value);
sp = getSharedPreferences("godv", Context.MODE_PRIVATE);
edit = sp.edit();
}
public void save(View v) {
String key = et_sp_key.getText().toString();
String value = et_sp_value.getText().toString();
edit.putString(key, value).commit();
Toast.makeText(Spactivity.this, "保存成功~", Toast.LENGTH_SHORT).show();
}
public void read(View v) {
String key = et_sp_key.getText().toString();
String string = sp.getString(key, null);
if(string==null){
Toast.makeText(Spactivity.this, "没有找到对应的值~", Toast.LENGTH_SHORT).show();
}else{
et_sp_value.setText(string);
}
}
}