標籤:style sha cat com div bool 介紹 stat try
sharedPreferences是通過xml檔案來做資料存放區的。
一般用來存放一些標記性的資料,一些設定資訊。
*********使用sharedPreferences儲存資料
public static boolean saveUserInfo(Context context, String username, String password) { try { //1使用Context建立一個SharePerference對象 SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //2SharePerference對象得到Editor對象 Editor edit = sharedPreferences.edit(); //3往Editor對象裡面添加資料 edit.putString("username",username); edit.putString("password",password); //4提交Editor對象 edit.commit(); return true; } catch (Exception e) { e.printStackTrace(); } return false; }
*********使用sharedPreferences讀取資料
public static Map<String, String> getUserInfo(Context context) { try { //1 使用Context建立一個SharePerference對象 SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //2SharePerference對象擷取存放的資料 String username = sharedPreferences.getString("username", ""); String password = sharedPreferences.getString("password", ""); HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("username", username); hashMap.put("password", password); return hashMap; } catch (Exception e) { e.printStackTrace(); } return null; }
通過PreferenceManager可以擷取一個預設的sharepreferences對象
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences介紹,用來做資料存放區