本文實(shí)例講述了Android在不使用數(shù)據(jù)庫的情況下存儲數(shù)據(jù)的方法。分享給大家供大家參考。具體分析如下:
在有些情況下我們不需要構(gòu)建數(shù)據(jù)庫,但是卻要將一些數(shù)據(jù)保存起來,等到程序下次運(yùn)行時(shí)調(diào)用,那么我們?nèi)绾巫瞿兀?/p>
1. 引用命名空間
import android.content.SharedPreferences;
2. 定義一個(gè)新類PictureGlobalDef,用來存儲數(shù)據(jù),在該類中定義:
public final static String APPSetting = "SettingFile";public final static String DEFAULT_SWITCH_MODE_KEY="default_switch_mode";public static boolean SWITCH_OPEN = false;
3. 在要引用數(shù)據(jù)SWITCH_OPEN 的地方:
SharedPreferences settingviewMode = getSharedPreferences( PictureNoteGlobalDef.APPSetting, 0);boolean bSwitch = settingviewMode.getBoolean( PictureNoteGlobalDef.DEFAULT_SWITCH_MODE_KEY , PictureNoteGlobalDef.SWITCH_OPEN );
4. 在要保存數(shù)據(jù)SWITCH_OPEN 的地方:
PictureNoteGlobalDef.SWITCH_OPEN = bSwitch;SharedPreferences settingviewMode = getSharedPreferences(APPSetting,0);SharedPreferences.Editor editor = settingviewMode.edit();editor.putBoolean(PictureNoteGlobalDef.DEFAULT_SWITCH_MODE_KEY , PictureNoteGlobalDef.SWITCH_OPEN ); editor.commit();
5. 讀,寫其他應(yīng)用程序的SharedPreferences
有些時(shí)候,我們需要讀寫其他應(yīng)用程序的SharedPreferences,這時(shí)應(yīng)該怎么辦呢?
讀取其他應(yīng)用程序的SharedPreferences關(guān)鍵是獲得其他應(yīng)用程序的Context:
Context tempContext = null;tempContext = createPackageContext("A.b",Context.CONTEXT_IGNORE_SECURITY);//此處A.b表示該應(yīng)用的包名
這樣就獲取了其他應(yīng)用程序的Context了
獲取到Context之后,就可以使用該Context的getSharedPreferences方法獲取ShaerdPreferences對象,從而按照1-4的方法進(jìn)行讀寫數(shù)據(jù)了。
希望本文所述對大家的Android程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選