在App中的很多地方都需要使用到數(shù)據(jù)信息,比如登陸保存的賬號(hào)信息,一次計(jì)算的結(jié)果等等笋庄,通常為了避免Activity之間傳遞數(shù)據(jù)的開銷彤灶,會(huì)將這些數(shù)據(jù)通過持久化來存儲(chǔ)。
有時(shí)候我們會(huì)把數(shù)據(jù)放在全局Appcation中展懈,其實(shí)销睁,這種做法是錯(cuò)誤的。當(dāng)App處于后臺(tái)時(shí)存崖,出現(xiàn)了內(nèi)存的時(shí)候冻记。這個(gè)Appcation很可能會(huì)被后臺(tái)殺掉,當(dāng)你再次恢復(fù)這個(gè)應(yīng)用時(shí)来惧,系統(tǒng)又會(huì)重新為這個(gè)應(yīng)用創(chuàng)建新的Appcation冗栗。而這個(gè)Appcation里面是沒有保存數(shù)據(jù)的,所以會(huì)導(dǎo)致空指針異常供搀。
為了應(yīng)用能夠更加穩(wěn)定隅居,我們很有必要使用持久化存儲(chǔ)來把數(shù)據(jù)保存在本地。
封裝SP的代碼
public class SpUtils {
/**
* 保存變量
*
* @param context
* @param key
* @param obj
*/
public static void save(Context context, String key, Object obj) {
// sp
SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
// 編輯器
Editor editor = sp.edit();
if (obj instanceof String) {
editor.putString(key, (String) obj);
} else if (obj instanceof Boolean) {
editor.putBoolean(key, (Boolean) obj);
}
editor.commit();// 保存
}
public static SharedPreferences get(Context context) {
// sp
SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
return sp;
}
}