【Android】資料的應用-使用sharedpreferences儲存資料

來源:互聯網
上載者:User

標籤:

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儲存資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.