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:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_1" android:hint="key"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_2" 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:text="保存" android:layout_weight="1" android:onClick="baocunonclick"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:text="获取" android:layout_weight="1" android:onClick="huoquonclick"/> </LinearLayout> </LinearLayout>
java
package com.example.chenshuai.test321; 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 Activitydata extends AppCompatActivity { EditText et_1; EditText et_2; SharedPreferences sp;//不能通过set方法存,通过edit存数据 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_activitydata); et_1 = (EditText)findViewById(R.id.et_1); et_2 = (EditText)findViewById(R.id.et_2); //1.获取SP的实例,指定了文件名和操作模式 sp = getSharedPreferences("mydata",MODE_PRIVATE); } //保存 public void baocunonclick(View view) { //1.获取key和value String key = et_1.getText().toString(); String value = et_2.getText().toString(); if (key.length()==0 || value.length()==0) { Toast.makeText(Activitydata.this, "key或value不为空", Toast.LENGTH_SHORT).show(); } else { //2.获取Editor SharedPreferences.Editor editor = sp.edit(); //3.放入键值对 editor.putString(key, value); //4.提交保存 boolean b = editor.commit(); if (b) { Toast.makeText(Activitydata.this, "保存成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Activitydata.this, "失败", Toast.LENGTH_SHORT).show(); } } } //获取 public void huoquonclick(View view) { //1.获取要读的key String key = et_1.getText().toString(); //2.读并设置文本框 et_2.setText(sp.getString(key,"没有发现key")); } }