为了更好地验证代码,我们首先改变AndroidManifest.xml,加入单元测试
14
并在 <application>内添加<uses-library android:name="android.test.runner" />
16
然后进行正式的编码:
第一步:编写MySharedPreferences01类用于存读文件1 package com.yxh.androidshareprefences01; 2 3 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import android.app.Activity; 8 import android.content.Context; 9 import android.content.SharedPreferences;10 11 public class MyShareprefences01 {12 private Context context;13 14 //构造方法15 public MyShareprefences01(Context context) {16 this.context=context;17 18 }19 //创建存放信息的方法20 public boolean saveShareprefences(String name,String age){21 boolean flag=false;22 //实例化SharedPreferences23 SharedPreferences share=context.getSharedPreferences("info",Activity.MODE_PRIVATE);24 //调用SharedPreferences下的接口,进行写入25 SharedPreferences.Editor editor=share.edit();26 //写入信息27 editor.putString("name",name);28 editor.putString("age", age);29 //提交信息,让数据持久化30 editor.commit();31 flag=true;32 return flag;33 }34 public MapreadShareprefences(){35 //实例化map用于接收信息36 Map map=new HashMap ();37 //实例化SharedPreferences38 SharedPreferences share=context.getSharedPreferences("info",Activity.MODE_PRIVATE);39 //根据KEY值取得信息40 String name=share.getString("name", "没有");41 String age=share.getString("age","0");42 //把取得的信息存入map43 map.put("name",name);44 map.put("age", age);45 46 return map;47 }48 49 50 }
第二步,进行代码测试
1 package com.yxh.androidshareprefences01; 2 3 import java.util.Map; 4 5 import android.app.Activity; 6 import android.content.Context; 7 import android.content.SharedPreferences; 8 import android.test.AndroidTestCase; 9 import android.util.Log;10 11 public class MyTest extends AndroidTestCase {12 private static String TAG="MyTest";13 14 public MyTest() {15 // TODO Auto-generated constructor stub16 }17 //对数据保存数据测试18 public void saveShareprefences(){19 Context context=getContext();20 MyShareprefences01 share=new MyShareprefences01(context);21 boolean flag=share.saveShareprefences("neusoft", "100");22 Log.i(TAG,"---->>"+flag);23 }24 //对读取数据测试25 public void readShareprefences(){26 Context context=getContext();27 MyShareprefences01 share=new MyShareprefences01(context);28 Mapmap=share.readShareprefences();29 Log.i(TAG,"---->>"+map.toString());30 }31 32 }
测试结果:
1 10-26 01:55:58.876: I/MyTest(3401): ---->>true2 10-26 02:02:42.716: I/MyTest(5120): ---->>{age=100, name=neusoft}