SharedPreferences儲存讀取資料

2021-07-28 13:37:07 字數 1193 閱讀 2317

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物件

sharedpreferences  sharedpreferences= 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();

SharedPreferences儲存資料

sharedprefrences是android中最容易理解的資料儲存技術,實際上sharedprefrences處理的就是乙個key value 鍵值對 sharedprefrences常用來成儲存一些輕量級的資料。使用方法 儲存資料 1 例項化sharedprefrences物件 2 例項化sh...

SharedPreferences儲存資料工具類

import android.content.context import android.content.sharedpreferences import android.content.sharedpreferences.editor public class preferenceutils r...

SharedPreferences儲存資料

適用範圍 儲存少量的資料,且這些資料的格式非常簡單 字串型 基本型別的值。比如應用程式的各種配置資訊 如是否開啟音效 是否使用震動效果 小遊戲的玩家積分等 解鎖口 令密碼等 context.mode private context.mode world readable context.mode w...