標籤:
為了更好地驗證代碼,我們首先改變AndroidManifest.xml,加入單元測試
1 <instrumentation2 android:name="android.test.InstrumentationTestRunner"3 android:targetPackage="com.yxh.androidshareprefences01" >4 </instrumentation>
並在 <application>內添加<uses-library android:name="android.test.runner" />
1 <application2 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 //執行個體化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 Map<String ,String > readShareprefences(){35 //執行個體化map用於接收資訊36 Map<String ,String > map=new HashMap<String, String>();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 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): ---->>true2 10-26 02:02:42.716: I/MyTest(5120): ---->>{age=100, name=neusoft}
Android資料存放區------2 共用參數