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);