1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.hanqi.testapp3.MainActivity" 11 android:orientation="vertical"> 12 13 <TextView 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" 16 android:text="Hello World!" /> 17 18 <Button 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content" 21 android:text="sp存储" 22 android:onClick="bt_OnClick"/> 23 24 <Button 25 android:layout_width="match_parent" 26 android:layout_height="wrap_content" 27 android:text="sp读取" 28 android:onClick="bt1_OnClick"/> 29 </LinearLayout>
1 package com.hanqi.testapp3; 2 3 import android.content.SharedPreferences; 4 import android.os.Bundle; 5 import android.support.v7.app.AppCompatActivity; 6 import android.view.View; 7 import android.widget.Toast; 8 9 public class MainActivity extends AppCompatActivity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 } 16 17 public void bt_OnClick(View v) 18 { 19 //1、得到SharedPreferences对象 20 SharedPreferences sharedPreferences = getSharedPreferences("abc", MODE_APPEND); 21 22 //2、得到编辑器 23 SharedPreferences.Editor editor = sharedPreferences.edit(); 24 25 //3、使用Editor添加数据 26 // editor.putString("b","xxxxxx"); 27 // editor.putLong("long",123456); 28 29 //移除数据 30 editor.remove("a"); 31 32 //4、提交保存 33 editor.commit(); 34 35 Toast.makeText(MainActivity.this, "保存数据成功", Toast.LENGTH_SHORT).show(); 36 } 37 38 public void bt1_OnClick(View v) 39 { 40 SharedPreferences sp = getSharedPreferences("abc",MODE_PRIVATE); 41 42 String str = sp.getString("b", "默认值"); 43 44 Toast.makeText(MainActivity.this, "key = b" + " value = " + str, Toast.LENGTH_SHORT).show(); 45 } 46 }