Giới thiệu
Trong Android có nhiều cácH lưu trữ dữ liệu với nhiều mục đích khác nhau:
- Sử dụng SQLite để lưu trữ các dữ liệu dưới dạng bảng, truy xuất theo phong cách database.
- Lưu trữ tập tin ở Internal Storage, External Storage.
- Lưu trữ dữ liệu trên server và thông qua webservice để thao tác với dữ liệu đó.
Bài viết này hướng dẫn 1 cách lưu trữ đơn giản trong Android là sử dụng SharedPreferences
.
Shared Preferences là gì?
Shared Preferences là 1 cách lưu trữ những dữ liệu dạng nguyên thủy (bool
, int
, float
, double
, String
) trong Android dưới dạng file XML với những cặp key/value, ví dụ lưu trữ điểm số của game.
Để làm việc với Shared Preferences, Android SDK có cung cấp 2 class là SharedPreferences
và SharePreferences.Editor
.
Lưu trữ và lấy dữ liệu với Shared Preferences
Tạo SharedPreferences và SharePreferences.Editor
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit();
- Dòng 1: đối số
SHARE_PREFERENCES_NAME
làString
, chỉ cần nhập tên file không cần nhập phần mở rộng file .xml.- Được lưu tại
DATA/data/[application package name]/shared_prefs/shared_preferences_name.xml
.
- Được lưu tại
- Dòng 2: để lưu trữ dữ liệu cần tạo 1 đối tượng
Editor
từsharedPreferences
.
Lưu dữ liệu vào SharedPreferences
Sau đó sử dụng các phương thức có tiền tố putX(String key, value)
để lưu trữ cặp key/value.
Sau khi đặt các giá trị thì gọi phương thức editor.apply()
hoặc editer.commit()
để tiến hành ghi các giá trị xuống ứng dụng dưới dạng file .xml.
Nếu đã đặt dữ liệu mà không gọi phương thức apply()
hoặc commit()
thì những thay đổi này vẫn không được ghi xuống file .xml, vì vậy nếu có thay đổi thì phải gọi phương thức apply()
hoặc commit()
để lưu trữ những thay đổi đó.
Ví dụ:
editor.putBoolean("key_name1", true); // Saving boolean
editor.putInt("key_name2", "int value"); // Saving int
editor.putFloat("key_name3", "float value"); // Saving float
editor.putLong("key_name4", "long value"); // Saving long
editor.putString("key_name5", "string value"); // Saving string
editer.apply(); // (*)
Nhận dữ liệu từ SharedPreferences
Để nhận dữ liệu từ SharedPreference
, không cần tạo đối tượng Editor
mà có thể sử dụng chính đối tượng sharedPreferences
với các phương thức là getX(String key, defaultValue)
:
Với X là boolean
, int
, float
, long
, String
, phương thức mô tả đúng giá trị ứng với key trong sharePreferences
. Nếu không có key sẽ trả về giá trị defaultValue
.
Ví dụ:
boolean userFirstLogin = sharedPreferences.getBoolean("key_name1", true); // getting boolean
int pageNumber = sharedPreferences.getInt("key_name2", 0); // getting int
float amount = sharedPreferences.getFloat("key_name3", 0.0f); // getting Float
long distance = sharedPreferences.getLong("key_name4", 0); // getting Long
String email = sharedPreferences.getString("key_name5", null); // getting String
Xoá dữ liệu (key/value) từ SharedPreferences
Sử dụng phương thức remove(key)
:
editor.remove("key_name3"); // delete data by key key_name3
editor.remove("key_name4"); // delete data by key key_name4
editer.apply(); // Apply changes
Xoá tất cả dữ liệu từ SharedPreferences
Sử dụng phương thức clear()
của đối tượng editor.
editor.clear();
editor.apply(); // Apply changes
Thực hành SharedPreferences
Tạo màn hình cài đặt và lưu trữ các cài đặt của game.
Tạo project có tên là SharedPreferences, giao diện sau khi tạo xong project:
File main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nguyennghia.sharedpreference.MainActivity">
<LinearLayout
android:id="@+id/ll_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="9">
<CheckBox
android:id="@+id/cb_volume"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="3"
android:button="@null"
android:checked="true"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
android:text="Volume" />
<SeekBar
android:id="@+id/sb_volume"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"
android:max="100" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="9">
<CheckBox
android:id="@+id/cb_sound_effect"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="3"
android:button="@null"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
android:text="Sound Effect" />
<SeekBar
android:id="@+id/sb_sound_effect"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"
android:max="100" />
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ll_settings"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Save" />
</RelativeLayout>
Tiếp theo là xử lý logic để lưu trữ các giá trị settings game sử dụng SharedPreferences
.
package com.example.nguyennghia.sharedpreference;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String SHARED_PREFERENCE_NAME = "SettingGame";
private CheckBox cbVolume;
private CheckBox cbSoundEffect;
private SeekBar sbVolume;
private SeekBar sbSoundEffect;
private Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbVolume = (CheckBox) findViewById(R.id.cb_volume);
cbSoundEffect = (CheckBox) findViewById(R.id.cb_sound_effect);
sbVolume = (SeekBar) findViewById(R.id.sb_volume);
sbSoundEffect = (SeekBar) findViewById(R.id.sb_sound_effect);
btnSave = (Button) findViewById(R.id.btn_save);
cbVolume.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b)
sbVolume.setVisibility(View.VISIBLE);
else
sbVolume.setVisibility(View.INVISIBLE);
}
});
cbSoundEffect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b)
sbSoundEffect.setVisibility(View.VISIBLE);
else
sbSoundEffect.setVisibility(View.INVISIBLE);
}
});
// Get value from sharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
boolean isVolume = sharedPreferences.getBoolean("volume", false);
boolean isSoundEffect = sharedPreferences.getBoolean("sound_effect", false);
int volumeValue = sharedPreferences.getInt("volume_value", 0);
int soundEffectValue = sharedPreferences.getInt("sound_effect_value", 0);
cbVolume.setChecked(isVolume);
cbSoundEffect.setChecked(isSoundEffect);
if (isVolume)
sbVolume.setProgress(volumeValue);
else
sbVolume.setVisibility(View.INVISIBLE);
if (isSoundEffect)
sbSoundEffect.setProgress(soundEffectValue);
else
sbSoundEffect.setVisibility(View.INVISIBLE);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("volume", cbVolume.isChecked());
editor.putBoolean("sound_effect", cbSoundEffect.isChecked());
if (cbVolume.isChecked())
editor.putInt("volume_value", sbVolume.getProgress());
else
editor.putInt("volume_value", 0);
if (cbSoundEffect.isChecked())
editor.putInt("sound_effect_value", sbSoundEffect.getProgress());
else
editor.putInt("sound_effect_value", 0);
// Save changes
editor.apply();
}
});
}
}
Khi thay đổi giá trị checkbox và seekbar, sau đó lưu lại và thoát ứng dụng. Vào lại ứng dụng thì thấy rằng phần cài đặt này giống như đã lưu ở trước đó.
Để chắc chắn hơn, mở Android Device Moniter để xem file .xml được lưu ở chỗ nào. Vào Tool
→ Android
→ Andorid Device Moniter
.
Trong mục File Explorer, tìm đến thư mục data/data.
Và tìm đến package com.example.nguyennghia.sharedpreference
sẽ thấy 1 thư mục có tên là shared_prefs chứa file XML đã lưu sử dụng SharedPreferences
trong Android.
Source code sử dụng trong bài viết này có thể download từ Github.