android的配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_sharedpreference"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="9" />
<instrumentation android:targetPackage="com.example.android_sharedpreference" android:name="android.test.InstrumentationTestRunner"></instrumentation>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="android.test.runner"></uses-library>
<activity
android:name="com.example.android_sharedpreference.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
下面是操作代码
package com.example.android_sharedpreference;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
public class MySharedpreference {
private Context context;
public MySharedpreference(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
public boolean saveMessage(String name,String pswd){
boolean flag=false;
SharedPreferences sharedPreferences=context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
//对数据进行编辑
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("name",name);
editor.putString("pswd", pswd);
flag=editor.commit();//将数据持久化
return flag;
}
public Map<String,Object>getMessage(){
Map<String, Object>map=new HashMap<String, Object>();
SharedPreferences sharedPreferences=context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name","");
String pswd=sharedPreferences.getString("pswd", "");
map.put("name", name);
map.put("pswd",pswd);
return map;
}
}
测试代码
import java.util.Map;
import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;
public class MyTest extends AndroidTestCase {
private String TAG="MyTest";
public void save(){
Context context=getContext();
MySharedpreference mySharedpreference=new MySharedpreference(context);
boolean flag=mySharedpreference.saveMessage("admin", "password");
Log.i(TAG,"-->"+flag);
}
public void find(){
Context context=getContext();
MySharedpreference mySharedpreference=new MySharedpreference(context);
Map<String, Object> map=mySharedpreference.getMessage();
Log.i(TAG, map.toString());
}
}
在Android系统中, 其配置文件的数据文件 以XML文件的形式保存在 /data/data/目录 /shared_prefs 目录下