Android shared preference dùng để lưu trữ dữ liệu đơn giản dạng key - value. Nội dung lưu trữ được lưu vào các file xml.
Khi bạn có nhu cầu lưu trữ dữ liệu đơn giản cho người dùng hoặc cấu hình cài đặt của ứng dụng thì có thể sử dụng tính năng này. Khi người dùng lưu trữ dữ liệu vào thì lúc tắt app đi và bật lại mọi lưu trữ vẫn còn nguyên. VD bạn có thể dùng lưu trữ trạng thái đăng nhập của người dùng hoặc trạng thái chơi game....
Android hỗ trợ 2 phương thức:
- getSharedPreferences: được gọi thông qua context và có thể truy cập tới nhiều preferences thông qua tên file.
- getPreferences: được gọi trong activity hiện tại và chỉ làm việc với 1 file duy nhất tương ứng của activity mà không cần chỉ ra tên file.
Các bước thực hiện
Bước 1: Trong layout của activity bạn tạo 2 nút bấm
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_save"
android:text="Save Pref"
android:onClick="SaveSharedPref"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_read"
android:onClick="RedSharedPref"
android:text="Read user"
/>
Bước 2: Trong file java của activity bạn viết 2 cái hàm cho sự kiện onClick của nút bấm. Chú ý tên class activity thì theo ứng dụng của bạn nhé.
public class LoginActivity extends AppCompatActivity {
SharedPreferences sharedPreferences; // khai báo thuộc tính cấp class để sử dụng chung trong các hàm
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// khởi tạo biến
sharedPreferences = getSharedPreferences("user_account", Context.MODE_PRIVATE);
}
public void SaveSharedPref(View view){
// khởi tạo biến editor để thực hiện thao tác ghi vào sharedpref
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("hoTen", "Nguyễn Văn A");
editor.putString("email", "[email protected]");
editor.commit(); // commit thì mới ghi xuống file.
}
public void RedSharedPref(View view){
// đọc dữ liệu từ shared pref
String user = sharedPreferences.getString("hoTen","");
String email = sharedPreferences.getString("email","");
Toast.makeText(getBaseContext(), "Họ và tên: " + user + "\nEmail: "+ email, Toast.LENGTH_SHORT).show();
}
}
Kết quả chạy như sau: