Android——使用SharedPreference儲存資料

來源:互聯網
上載者:User

標籤:android   style   blog   http   ar   color   使用   sp   on   

public interface SharedPreferences

匯入:

  android.content.SharedPreferences;

Overiview:

  主要用於儲存apk的一些屬性資料,例如:視窗大小,音量等preference資料。

主要方法:

  

使用:

  (1)通過getSharedPreferences(string name,int mode)擷取SharedPreferences的執行個體

  (2)如果需要存入資料,使用SharedPreferences.Editor擷取一個Editor,使用editor.putString(string key,string value)

    editor.commit()存入資料

  (3)讀取資料使用獲得的執行個體.getString(string key,string “”);//第二個參數預設值

程式碼範例:

  a) 資料存入

 //執行個體化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(); 

  b) 讀出資料

 [code] //同樣,在讀取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——使用SharedPreference儲存資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.