<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="white-space:pre"> </span>sharedPreference可以將一些簡單的信息以xml形式保存到SD卡上,比如登陸時的用戶名和密碼,這樣在下次登陸時,用戶不必再從數據庫或網絡獲取數據了。提升系統性能。下面簡單記錄一下sharedpreference的用法。</span>
package com.example.sharedpreferences;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
public class MySharedPreference {
private Context context;
public MySharedPreference(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
public boolean saveMessage(String name, String pwd) {
boolean flag = false;
SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
//對數據編輯
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name);
editor.putString("pwd", pwd);
flag = editor.commit();
return flag;
}
public Map<String, Object> getMessage(){
SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo",Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name","");
String pwd = sharedPreferences.getString("pwd","");
Map<String,Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("pwd", pwd);
return map;
}
}