Trong bài hướng dẫn này, chúng ta sẽ khám phác cách lưu trữ dữ liệu trong Android bằng SharedPreferences.
Tổng quan về Android Shared Preferences
Shared Preferences
cho phép các activity và ứng dụng lưu lại preferences dưới dạng các cặp key-value
(tương tự như Map
), và dữ liệu này sẽ được duy trì ngay cả khi người dùng đóng ứng dụng. Android lưu các cài đặt của Shared Preferences
dưới dạng file XML trong thư mục shared_prefs
tại đường dẫn DATA/data/{application package}
. Có thể lấy đường dẫn đến thư mục DATA
bằng cách gọi Environment.getDataDirectory()
.
SharedPreferences
chỉ dành riêng cho ứng dụng, tức là dữ liệu sẽ bị mất khi:
- Gỡ cài đặt ứng dụng
- Xóa dữ liệu ứng dụng (thông qua mục Settings)
Đúng như tên gọi, mục đích chính của Shared Preferences
là để lưu trữ các cấu hình của người dùng, ví dụ như các cài đặt riêng hoặc duy trì trạng thái đăng nhập cho ứng dụng.
Để truy cập vào các preferences, chúng ta có ba API để lựa chọn:
getPreferences()
: sử dụng bên trong Activity để truy cập các preferences của riêng Activity đó.getSharedPreferences()
: sử dụng bên trong Activity (hoặcContext
khác của ứng dụng) để truy cập các preferences ở cấp độ ứng dụng.getDefaultSharedPreferences()
: sử dụng trênPreferenceManager
để lấy đối tượngSharedPreferences
, hoạt động phối hợp với framework quản lý preference chung của Android.
Trong bài hướng dẫn này, chúng ta sẽ sử dụng getSharedPreferences()
. Phương thức này được định nghĩa như sau: getSharedPreferences(String PREFS_NAME, int mode)
. Trong đó, PREFS_NAME
là tên của file. mode
là chế độ hoạt động.
Các chế độ hoạt động có thể áp dụng bao gồm:
MODE_PRIVATE
: chế độ mặc định, file được tạo chỉ có thể được truy cập bởi ứng dụng đã gọi.MODE_WORLD_READABLE
: Tạo file mà các ứng dụng khác có thể đọc là rất nguy hiểm và có khả năng gây ra lỗ hổng bảo mật.MODE_WORLD_WRITEABLE
: Tạo file mà các ứng dụng khác có thể ghi là rất nguy hiểm và có khả năng gây ra lỗ hổng bảo mật.MODE_MULTI_PROCESS
: Phương thức này sẽ kiểm tra các sửa đổi của preferences ngay cả khi instance củaShared Preference
đã được tải.MODE_APPEND
: Chế độ này sẽ nối các preference mới vào các preference đã tồn tại.MODE_ENABLE_WRITE_AHEAD_LOGGING
: Cờ mở database. Khi được thiết lập, nó sẽ bật tính năng ghi log trước khi ghi (write-ahead logging) theo mặc định.
Khởi tạo
Chúng ta cần một Editor
để chỉnh sửa và lưu các thay đổi trong SharedPreferences
. Có thể sử dụng đoạn code sau để lấy đối tượng SharedPreferences
.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Lưu trữ dữ liệu
editor.commit()
được dùng để lưu các thay đổi vào SharedPreferences
.
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
Truy xuất dữ liệu
Dữ liệu có thể được truy xuất từ SharedPreferences
đã lưu bằng cách gọi các phương thức get
như sau:
pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Xóa dữ liệu
remove(“key_name”)
được dùng để xóa một giá trị cụ thể. clear()
được dùng để xóa toàn bộ dữ liệu.
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
Cấu trúc Project
Code cho Project Android Shared Preferences
Layout activity_main.xml
bao gồm hai EditText
để lưu và hiển thị tên và email. Ba Button
sẽ triển khai các sự kiện onClick
tương ứng trong MainActivity
.
<RelativeLayout xmlns:android="<https://schemas.android.com/apk/res/android>"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="Save"
android:text="Save" />
<Button
android:id="@+id/btnRetr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Get"
android:text="Retrieve" />
<Button
android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/etEmail"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="clear"
android:text="Clear" />
<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress"
android:layout_below="@+id/etName"
android:layout_marginTop="20dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/etEmail"
android:layout_alignStart="@+id/etEmail" />
</RelativeLayout>
File MainActivity.java
được dùng để lưu và truy xuất dữ liệu thông qua các key.
package com.journaldev.sharedpreferences;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
mypreference
là tên của file nơi lưu trữ các cặp key-value
của Shared Preferences
. Hình ảnh bên dưới cho thấy kết quả cuối cùng của project.
Bài hướng dẫn đến đây là kết thúc. Bạn có thể tải project Android Shared Preferences về từ liên kết bên dưới.
[Tải xuống Dự án Mẫu Android Shared Preferences]