在Android開發(fā)中,在儲存少量的數(shù)據(jù)時敲霍,個人感覺SharedPreferences是最好的選擇,SharedPreferences是以鍵值對的方式進行儲存膘格,支持boolean甘萧,int萝嘁,float,long扬卷,String以及Set<String>牙言,使用方法如下:
先在類中進行聲明:
private SharedPreferences mSharedPreferences;
//mEditor用于編輯SharedPreferences
private SharedPreferences.Editor mEditor;
在onCreate()方法中進行初始化:
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
//獲得SharedPreferences的Editor對象
mEditor = mSharedPreferences.edit();
//添加一個名稱為“isFirstEnter”,值為false的鍵值對
mEditor.putBoolean(“isFirstEnter”,false);
mEditor.putInt("version",1);
mEditor.putFloat("versionCode",1.0f);
mEditor.putLong("long",0);
mEditor.putString("string","hello world");
Set<String> set = new HashSet<>();
set.add("Tony");
set.add("jack");
mEditor.putStringSet("set<string>",set);
//編輯完成后不要忘記提交
mEditor.commit();
上面是儲存的一條數(shù)據(jù)怪得,那么想讀出這條數(shù)據(jù)怎么辦呢咱枉?方法如下:
/*第一個參數(shù)是已存鍵值對的名稱,第二個參數(shù)為默認值徒恋,在找不到要讀的鍵值對時蚕断,該方法就返回自己設(shè)置的默認值,即true入挣,當然也可以為false亿乳,根據(jù)需要自己設(shè)置*/
mSharedPreferences.getBoolean(“isFirstEnter”,true)
同理,讀取其他類型的數(shù)據(jù)就調(diào)用相應(yīng)的get方法径筏,使用起來是不是很簡單葛假?
PS:開發(fā)了一個制作二維碼的App,有興趣的可以試一試~ ^ _ ^
創(chuàng)意二維碼制作