Android應用開發SharedPreferences儲存資料的使用方法

來源:互聯網
上載者:User

標籤:資料存放區   android應用   

1、SharedPreferences是Android中最容易理解的資料存放區技術,實際上SharedPreferences處理的就是一個key-value(鍵值對)。SharedPreferences常用來儲存一些輕量級的資料


public void setShareValue() {

 // 執行個體化SharedPreferences對象(第一步) 儲存到本地xml檔案的name---test

 SharedPreferences mySharedPreferences = getSharedPreferences("test", Activity.MODE_PRIVATE);

 // 執行個體化SharedPreferences.Editor對象(第二步) SharedPreferences.Editor editor = mySharedPreferences.edit(); 

// 用putString的方法儲存資料 

editor.putString("name", "tom"); 

editor.putString("password", "123");

 // 提交當前資料 editor.commit(); 

// 使用toast資訊氣球提示成功寫入資料

 Toast.makeText(this, "資料成功寫入SharedPreferences!", Toast.LENGTH_LONG).show(); 

}


2、執行以上代碼,SharedPreferences將會把這些資料儲存在test.xml檔案中,可以在File Explorer的data/data下匯出該檔案,並查看。 那麼已經儲存好的資料如何讀取出來呢。我們來看


 public void getShareValue() {

 // 同樣,在讀取SharedPreferences資料前要執行個體化出一個SharedPreferences對象

 // 擷取本地xml檔案name---test 

SharedPreferences sharedPreferences = getSharedPreferences("test", Activity.MODE_PRIVATE);

 // 使用getString方法獲得value,注意第2個參數是value的預設值 

String name = sharedPreferences.getString("name", "當name不存在時此值位預設值"); 

String habit = sharedPreferences.getString("password", "當password不存在時的預設值"); 

// 使用toast資訊氣球顯示資訊 

Toast.makeText(this, "讀取資料如下:" + "\n" + "name:" + name + "\n" + "password:" + 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.