Thứ Sáu, 28 tháng 6, 2013

SharedPreference android là gì

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); // 0 - for private mode
Editor editor = pref.edit();
  Để lưu trữ data mình dùng:
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
 
editor.commit(); // commit changes
 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 
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
  Để clear tất cả data dùng :
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
 
editor.commit(); // commit changes

Không có nhận xét nào:

Đăng nhận xét