为了更好地验证代码,我们首先改变AndroidManifest.xml,加入单元测试
1 <instrumentation 2 android:name="android.test.InstrumentationTestRunner" 3 android:targetPackage="com.yxh.androidshareprefences01" > 4 </instrumentation>
并在 <application>内添加<uses-library android:name="android.test.runner" />
1 <application 2 android:allowBackup="true" 3 android:icon="@drawable/ic_launcher" 4 android:label="@string/app_name" 5 android:theme="@style/AppTheme" > 6 <uses-library android:name="android.test.runner" />
然后进行正式的编码:
第一步:编写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 //实例化SharedPreferences 23 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 Map<String ,String > readShareprefences(){ 35 //实例化map用于接收信息 36 Map<String ,String > map=new HashMap<String, String>(); 37 //实例化SharedPreferences 38 SharedPreferences share=context.getSharedPreferences("info",Activity.MODE_PRIVATE); 39 //根据KEY值取得信息 40 String name=share.getString("name", "没有"); 41 String age=share.getString("age","0"); 42 //把取得的信息存入map 43 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 stub 16 } 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 Map<String,String> map=share.readShareprefences(); 29 Log.i(TAG,"---->>"+map.toString()); 30 } 31 32 }
测试结果:
1 10-26 01:55:58.876: I/MyTest(3401): ---->>true 2 10-26 02:02:42.716: I/MyTest(5120): ---->>{age=100, name=neusoft}
时间: 2024-10-26 18:01:48