Android app系統設定介面 資料的儲存與讀取 SharedPreferences 的正確使用
很開心的是經歷過兩個多月的努力,專案在11月份即將要交付使用,基礎功能已經完成,剩下的是系統設定介面沒有開發完畢,如下圖:
很顯然要實現的功能是幾個介面要顯示很多資料,要依據某一項進行排序,當勾選的選項被選中時,選單切換到該介面時,就要按照這個欄位進行排序,所以需求是使用者點選的欄位,需要儲存下來,當用戶退出程式,再次進入的時候,需要獲得已經儲存的欄位的值,也就是顯示打鉤的那項,解決方案如下:
第一個方案:腦子裡第一個冒出來的就是使用sqlite來儲存資料,這樣每次進入應用的時候,重新從資料庫裡面獲取該欄位的值,不過鑑於儲存資料不多,都是一些string、int或者boolean型別,用資料庫有點大材小用,(關於sqlite的部分有興趣的同學可以參考別的文章,這裡就不多說了)。
第二個方案:是公司同事(我師傅),他在登陸介面為了記錄使用者的登陸狀態,採用了類似於windows裡的登錄檔的功能來儲存登陸狀態,Android的系統屬性相當於windows的登錄檔,由key和value組成,且都是核心系統的一個基本機制。相對於windows的登錄檔,Android的系統屬性要簡單一些,它沒有windows登錄檔的樹狀結構,而只是一個列表,也就是說沒有父子關係。value有string,int,long,boolean,但是設定只能通過字串方式。(這是從該博文截取出來的,有興趣的可以參考:android “登錄檔”),這個方案其實和第三個方案,功能是類似的,只不過範圍更大,介紹第三個方案。
第三個方案也就是本博文提到的Sharepreferences,這個類實現的功能我的理解是:儲存一個應用程式的基本型別變數,儲存在該應用的xml檔案下(data/data/包名/shared_prefs/),可以雙擊開啟,就可以看到我們儲存的變數,具體的sharepreferences的用法我就不多講了,有很多很好的博文:sharepreferences博文1,其實真的很好用,只要在我的應用中:當用戶點選了某一個項,通過監聽textview點選事件,更換帶鉤的背景圖片,存下shareperferences的變數,在使用者再次登入的時候,然後獲取剛才儲存的變數,只需要拿到該key,就可以拿到value,分享一個一位前輩提供的sharepreferences的工具類,不用再那麼麻煩的建立和儲存了,再次感謝:
package client.verbank.mtp.allone.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* SharedPreferences操作工具類
*
*/
public class SharepreferencesUtilSystemSettings {
public final static String SETTING = "Setting";
public static void putValue(Context context, String key, int value) {
Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
.edit();
sp.putInt(key, value);
sp.commit();
}
public static void putValue(Context context, String key, boolean value) {
Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
.edit();
sp.putBoolean(key, value);
sp.commit();
}
public static void putValue(Context context, String key, String value) {
Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
.edit();
sp.putString(key, value);
sp.commit();
}
public static int getValue(Context context, String key, int defValue) {
SharedPreferences sp = context.getSharedPreferences(SETTING,
Context.MODE_PRIVATE);
int value = sp.getInt(key, defValue);
return value;
}
public static boolean getValue(Context context, String key, boolean defValue) {
SharedPreferences sp = context.getSharedPreferences(SETTING,
Context.MODE_PRIVATE);
boolean value = sp.getBoolean(key, defValue);
return value;
}
public static String getValue(Context context, String key, String defValue) {
SharedPreferences sp = context.getSharedPreferences(SETTING,
Context.MODE_PRIVATE);
String value = sp.getString(key, defValue);
return value;
}
}
具體我的邏輯程式碼在上一篇博文有,有問題歡迎交流,謝謝各位!!!