Giới thiệu
Trong Android có khác nhiều các lưu trữ dữ liệu với nhiều mục đích khác nhau. Ví dụ các bạn có thể sử dụng SQLite để lưu trữ các data dưới dạng table hay nói cách khác chính là databasse, lưu trữ file ở Internal Storage, External Storeage. Hoặc có thể lưu trữ dữ liệu trên server và thông qua webservice để thao tác với dữ liệu đó. Nhưng trong bài viết này tôi sẽ hướng dẫn một các lưu trữ đơn giản và dễ nhất trong Android, đó là sử dụng Shared Preferences.
Shared Preferences là gì
Shared Preferences là một cách lưu trữ những dữ liệu dạng nguyên thuỷ (bool, int, float, double, String) trong android dưới dạng file xml với những cặp key – value. Ví dụ như lưu trữ high score của game…
Để làm việc với Shared Preferences thì Android SDK có cung cấp cho chúng ta hai class chính đó là SharedPreferences và SharePreferences.Editor.
Lưu trữ và lấy dữ liệu với Shared Preferences
Tạo SharedPerferences
1 |
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); |
Đối số SHARE_PREFERENCES_NAME là một String. Bạn chỉ cần nhập tên file thôi chứ không cần nhập đuôi file .xml. Vì mặc định sẽ có đuôi là .xml.
Lưu trữ
Để lưu trữ data chúng ta cần tạo một đối tượng Editor từ sharedPreferences đã tạo ở tên bằng cách:
1 |
SharedPreferences.Editor editor = sharedPreferences.edit(); |
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 put các giá trị thì chúng ta gọi phương thức editor.apply(); hoặc editer.commit(); để tiến hành ghi các giá trị ở trên xuống ứng dụng dưới dạng file .xml.
File .xml được lưu có đường dẫn như sau:
1 |
DATA/data/[application package name]/shared_prefs/shared_preferences_name.xml |
Lưu ý: Nếu các bạn đã put data 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 hãy nhớ rằng nếu có thay đổi thì thì phải gọi phương thức apply() hoặc commit() để lưu trữ những thay đổi đó.
Ví dụ:
1 2 3 4 5 6 7 8 |
editor.putBoolean("key_name1", true); // Saving boolean - true/false editor.putInt("key_name2", "int value"); // Saving integer editor.putFloat("key_name3", "float value"); // Saving float editor.putLong("key_name4", "long value"); // Saving long editor.putString("key_name5", "string value"); // Saving string // Save the changes in SharedPreferences editer.apply(); |
Nhận data từ SharedPreferences
Để nhận dữ liệu từ SharedPreference chúng ta không cần tạo đối tượng Editor mà có thể sử dụng ngay 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 tả về đúng gái trị ứng với key trong sharePreferences. Nếu không có key sẽ trả về giá trị defaultValue.
Ví dụ:
1 2 3 4 5 |
boolean userFirstLogin = sharedPreferences.getBoolean("key_name1", true); // getting boolean int pageNumber = sharedPreferences.getInt("key_name2", 0); // getting Integer 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á Key từ SharedPreferences
Để xoá key chúng ta sử dụng phương thức remove(key) của editor.
1 2 3 4 5 |
editor.remove("key_name3"); // will delete key key_name3 editor.remove("key_name4"); // will delete key key_name4 // Save the changes in SharedPreferens editer.apply(); |
Xoá tất cả data SharedPreferences
Sử dụng method clear() của đối tượng editor.
1 2 |
editor.clear(); editor.apply(); // Save changes |
Thực hành
Source code sử dụng trong bài viết này các bạn có thể dowload từ đây
Tạo project có tên là SharedPreferences. Giao diện sau khi tạo xong project:
Trong ví dụ thực hành này tôi sẽ làm ví dụ là một màn hình settings của game như sau:
File main_activity.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
<?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 sẽ là phần xử lý logic để lưu trữ các giá trị settings game sử dụng SharedPreferences.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
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 shared preferences. 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 change editor.apply(); } }); } } |
Các bạn hãy làm và chạy lại sẽ thấy khi chúng ta thay đổi giá trị checkbox và seekbar sau đó lưu lại. Thì sau khi vào lại thì chúng ta thấy rằng phần setting này giống như chúng ta đã lưu ở trước đó.
Để chắc chắn hơn các bạn mở Android Device Moniter lên để xem file .xml được lưu ở chổ nào.
Vào Tool > Android > Andorid Device Moniter
Trong mục File Explorer, chúng ta tìm đến thư mục data/data
Và tìm đến pakage của bạn (của mình là com.example.nguyennghia.sharedpreference) sẽ thấy một thư mục có tên là shared_prefs chứa file xml mà bạn đã lưu sử dụng SharedPreferences trong Android.
Kết luận
Trên đây tôi đã giới thiệu các bạn các lưu trữ dữ liệu nhất trong Android sử dụng SharedPreferences cũng như ví dụ, áp dụng cụ thể để giúp các bạn hiểu được sâu hơn. Tiếp đến bài tiếp theo chúng ta sẽ cùng nhau tìm hiểu các lưu trữ sử dụng SQLite. Nếu có bất cứ thắc mắc nào các bạn có thể để lại bình luận ở dưới bài viết hoặc có thể liên hệ với fanpage Eitguide Android để được giải đáp.
String is not a primitive type