DataActivity.java
package com.hanqi.test2; 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 DataActivity1 extends AppCompatActivity { EditText et_1; EditText et_2; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_data1); et_1=(EditText)findViewById(R.id.et_1); et_2=(EditText)findViewById(R.id.et_2); sp=getSharedPreferences("mydata",MODE_PRIVATE); } public void bt_1onclick(View v){ String key= et_1.getText().toString(); String value= et_2.getText().toString(); if (key.length()==0 || value.length()==0){ Toast.makeText(DataActivity1.this, "key,value不能为空", Toast.LENGTH_SHORT).show(); } SharedPreferences.Editor editor= sp.edit(); editor.putString(key,value); boolean b = editor.commit(); if (b){ Toast.makeText(DataActivity1.this, "yes", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(DataActivity1.this, "no", Toast.LENGTH_SHORT).show(); } } public void bt_2onclick(View v){ String key = et_1.getText().toString(); et_2.setText(sp.getString(key,"没有发现key")); } }
layout_data1.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:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.hanqi.test2.DataActivity1" 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"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="保存" android:onClick="bt_1onclick"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="读取" android:onClick="bt_2onclick"/> </LinearLayout> </LinearLayout>