Dùng để lưu trữ data trong file xml, có thể được dùng bởi application hoặc package khác.
Khởi động ta dùng cách thức getSharedPreferences() .
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
|
Để lưu trữ data mình dùng:
editor.putBoolean("key_name", true);
editor.putString("key_name", "string value");
editor.putInt("key_name", "int value");
editor.putFloat("key_name", "float value");
editor.putLong("key_name", "long value");
editor.commit();
|
Mình tạo biến editor để có thể edit giá trị trong object SharedPreferences.
Lệnh commit() để lưu thay đổi.
Để lấy lại data mình dùng
pref.getString("key_name", null);
pref.getInt("key_name", null);
pref.getFloat("key_name", null);
pref.getLong("key_name", null);
pref.getBoolean("key_name", null);
|
Để clear tất cả data dùng :
editor.remove("name");
editor.remove("email");
editor.commit();
|
Không có nhận xét nào:
Đăng nhận xét