標籤:
Android應用開發SharedPreferences儲存資料的使用方法
SharedPreferences是Android中最容易理解的資料存放區技術,實際上SharedPreferences處理的就是一個key-value(索引值對)SharedPreferences常用來儲存一些輕量級的資料。
1、使用SharedPreferences儲存資料方法如下:
//執行個體化SharedPreferences對象(第一步)
SharedPreferences mySharedPreferences= getSharedPreferences("test",
Activity.MODE_PRIVATE);
//執行個體化SharedPreferences.Editor對象(第二步)
SharedPreferences.Editor editor = mySharedPreferences.edit();
//用putString的方法儲存資料
editor.putString("name", "Karl");
editor.putString("habit", "sleep");
//提交當前資料
editor.commit();
//使用toast資訊氣球提示成功寫入資料
Toast.makeText(this, "資料成功寫入SharedPreferences!" , Toast.LENGTH_LONG).show();
執行以上代碼,SharedPreferences將會把這些資料儲存在test.xml檔案中,可以在File Explorer的data/data/相應的包名/test.xml 下匯出該檔案,並查看。
2、使用SharedPreferences讀取資料方法如下:
//同樣,在讀取SharedPreferences資料前要執行個體化出一個SharedPreferences對象
SharedPreferencessharedPreferences= getSharedPreferences("test",
Activity.MODE_PRIVATE);
// 使用getString方法獲得value,注意第2個參數是value的預設值
String name =sharedPreferences.getString("name", "");
String habit =sharedPreferences.getString("habit", "");
//使用toast資訊氣球顯示資訊
Toast.makeText(this, "讀取資料如下:"+"\n"+"name:" + name + "\n" + "habit:" + habit,
Toast.LENGTH_LONG).show();
【Android】資料的應用-使用sharedpreferences儲存資料