Android學習筆記-儲存資料的實現方法2-SharedPreferences

來源:互聯網
上載者:User

Android學習筆記-儲存資料的實現方法2-SharedPreferences
Android下,資料的儲存,前面介紹過了,把資料儲存到記憶體以及SD卡上,這次我們就介紹一下,更為常用的採用SharedPreferences的方式來儲存資料, 1,得到SharedPreferences的對象, 2,用SharedPreferences得到編輯器,就是Edit(本質上是個map) 3,往裡面放資料,放完後,要記得這時一個事務,要記得提交commit。   public static void saveUserInfo(Context context,String username,String password){ SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE); //得到sp的編輯器 Editor edit = sp.edit(); edit.putString("username", username); edit.putString("password", password); //類似與資料庫的事物,保證資料同時提交成功 edit.commit();   資料儲存好了,怎麼把資料讀取出來呢,其實剛剛報訊的資料,就是一個xml檔案,它的位置是/data/data/包名/shared_prefs(新產生的)/,這裡就是程式產生xml的路徑了, 讀取的時候,就是先得到SharedPreferences的對象,然後,在通過key就可以得到相應餓value了,較為便捷。    SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE); String username = sp.getString("username", ""); String password = sp.getString("password", ""); et_username.setText(username); et_password.setText(password);

聯繫我們

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