Chuyển đến nội dung chính

Tối ưu Android Shared Preferences

Giới thiệu

Xin chào các bạn, hôm nay mình xin giới thiệu với các bạn một chủ đề không quá xa lạ với các bạn lập trình viên Android, đó là SharedPreferences. Chắc các bạn đều đã biết hết công dụng của SharedPreferences là dùng để lưu trữ dữ liệu theo dạng key-values. Tư tưởng cơ bản của SharedPreferences chỉ là làm cách nào để bạn có thể ghi dữ liệu (Write to Shared Preferences) và đọc dữ liệu đã lưu (Read from Shared Preferences).
Nếu bạn thực sự chưa biết về SharedPreferences thì có thể xem qua một chút ở Google Developer hoặc là bài viết này Android SharedPreference
Tuy nhiên ở bài này mình sẽ chia sẻ một cách dùng SharedPreferences sao cho tốt nhất có thể.

Đặt vấn đề

Chắc hẳn trong khi code ứng dụng Android, các bạn từng phải dùng các đoạn code kiểu như này nhiều lần
SharedPreference sharedPrefs = getSharedPreference(“MySharedPreference”, MODE_PRIVATE);
sharedPrefs.put(key, "something");
hay là
SharedPreference sharedPrefs = getSharedPreference(“MySharedPreference”, MODE_PRIVATE);
sharedPrefs.get(key, "");
Nếu điều này cứ lặp lại nhiều thì có lẽ bạn sẽ thấy nó thật ngớ ngẩn phải không nào? Vậy sao chúng ta không cùng tìm cách tối ưu những đoạn code như này nhỉ? Hãy cùng thực hiện nào!

Tiến hành

Mình muốn có một class SharedPrefs thực hiện toàn bộ việc tạo SharedPreferencesput và get dữ liệu. Mình hiện thực hóa bằng cách tạo một class SharedPrefs ở dạng Singleton như sau:
SharedPrefs.java
package com.quanda.sharedprefs.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.quanda.sharedprefs.App;

public class SharedPrefs {
    private static final String PREFS_NAME = "share_prefs";
    private static SharedPrefs mInstance;
    private SharedPreferences mSharedPreferences;

    private SharedPrefs() {
        mSharedPreferences = App.self().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    public static SharedPrefs getInstance() {
        if (mInstance == null) {
            mInstance = new SharedPrefs();
        }
        return mInstance;
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key, Class<T> anonymousClass) {
        if (anonymousClass == String.class) {
            return (T) mSharedPreferences.getString(key, "");
        } else if (anonymousClass == Boolean.class) {
            return (T) Boolean.valueOf(mSharedPreferences.getBoolean(key, false));
        } else if (anonymousClass == Float.class) {
            return (T) Float.valueOf(mSharedPreferences.getFloat(key, 0));
        } else if (anonymousClass == Integer.class) {
            return (T) Integer.valueOf(mSharedPreferences.getInt(key, 0));
        } else if (anonymousClass == Long.class) {
            return (T) Long.valueOf(mSharedPreferences.getLong(key, 0));
        }
        return null;
    }

    public <T> void put(String key, T data) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        if (data instanceof String) {
            editor.putString(key, (String) data);
        } else if (data instanceof Boolean) {
            editor.putBoolean(key, (Boolean) data);
        } else if (data instanceof Float) {
            editor.putFloat(key, (Float) data);
        } else if (data instanceof Integer) {
            editor.putInt(key, (Integer) data);
        } else if (data instanceof Long) {
            editor.putLong(key, (Long) data);
        }
        editor.apply();
    }

    public void clear() {
        mSharedPreferences.edit().clear().apply();
    }
}
Để có thể tạo SharedPreferences thì mình cần có context, nhưng việc dùng context của Application giúp mình không cần phải truyền thêm gì vào hàm khởi tạo mà vẫn thực hiện được việc tạo SharedPreferences theo kiểu Singleton như ý mình mong muốn. Để làm được điều đó thì mình cần tạo một class App extends Application,
App.java
package com.quanda.sharedprefs;

import android.app.Application;
import com.google.gson.Gson;

public class App extends Application {
    private static App mSelf;

    public static App self() {
        return mSelf;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mSelf = this;
    }
}
Và các bạn nhớ là phải thêm App vào trong manifest như sau
Manifest.xml
<application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".main.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
Có vẻ khá đơn giản phải không các bạn, bây giờ mồi khi cần sử dụng SharedPreferences, các bạn chỉ cần gọi như dưới đây:
MainActivity.java
public static final String CURRENT_ID = "current_id";
public static final String CURRENT_NAME = "current_name";

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPrefs.getInstance().put(CURRENT_ID, 123);
        SharedPrefs.getInstance().put(CURRENT_NAME, "Dang Anh Quan");

        SharedPrefs.getInstance().get(CURRENT_ID, Integer.class);
        SharedPrefs.getInstance().get(CURRENT_NAME, String.class);
    }

Đã đủ chưa nhỉ?

Có vẻ như vẫn còn thiếu một điều gì đó, à đúng rồi, khi các bạn muốn lưu dữ liệu là một object của class không thuộc nhóm cơ bản thì sao nhỉ? Có lẽ chúng ta cần cải tiến thêm một chút nữa ở chỗ put và get.

Put object

Trước tiên ta cùng đi sửa hàm put, để có thể put một object của một class, khác với các class thuộc kiểu cơ bản vào SharedPreferences, thì bạn cần convert object đó thành dạng String nhờ thư viện Gson.
Chúng ta thêm dependencies cho build.gradle của module app
build.gradle
dependencies {
    ....
    compile 'com.google.code.gson:gson:2.8.1'
}
Sau đó chúng ta cập nhật lại class App một chút để bổ sung Gson
App.java
package com.quanda.sharedprefs;

import android.app.Application;

import com.google.gson.Gson;

public class App extends Application {

    private static App mSelf;
    private Gson mGSon;

    public static App self() {
        return mSelf;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mSelf = this;
        mGSon = new Gson();
    }

    public Gson getGSon() {
        return mGSon;
    }
}
Và giờ thì chúng ta cập nhật lại hàm put ở trong SharedPrefs
SharedPrefs.java
public <T> void put(String key, T data) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        if (data instanceof String) {
            editor.putString(key, (String) data);
        } else if (data instanceof Boolean) {
            editor.putBoolean(key, (Boolean) data);
        } else if (data instanceof Float) {
            editor.putFloat(key, (Float) data);
        } else if (data instanceof Integer) {
            editor.putInt(key, (Integer) data);
        } else if (data instanceof Long) {
            editor.putLong(key, (Long) data);
        } else {
            editor.putString(key, App.self().getGSon().toJson(data));
        }
        editor.apply();
    }

Get object

Như vậy là việc put object đã xong, giờ thì việc còn lại của chúng ta là làm sao để get object đó ra mà thôi. Chúng ta vẫn tiếp tục sử dụng Gson để thực hiện việc get object này. Thay vì return null ở cuối cùng của hàm get, chúng ta sửa lại thành return object với kiểu class đã đưa vào.
SharedPrefs.java
@SuppressWarnings("unchecked")
    public <T> T get(String key, Class<T> anonymousClass) {
        if (anonymousClass == String.class) {
            return (T) mSharedPreferences.getString(key, "");
        } else if (anonymousClass == Boolean.class) {
            return (T) Boolean.valueOf(mSharedPreferences.getBoolean(key, false));
        } else if (anonymousClass == Float.class) {
            return (T) Float.valueOf(mSharedPreferences.getFloat(key, 0));
        } else if (anonymousClass == Integer.class) {
            return (T) Integer.valueOf(mSharedPreferences.getInt(key, 0));
        } else if (anonymousClass == Long.class) {
            return (T) Long.valueOf(mSharedPreferences.getLong(key, 0));
        } else {
            return (T) App.self().getGSon().fromJson(mSharedPreferences.getString(key, ""), anonymousClass);
        }
    }
Ngoài ra nếu bạn muốn thay đổi default value khi get SharedPrefs thì bạn có thể overload thêm một hàm nữa như sau:
@SuppressWarnings("unchecked")
    public <T> T get(String key, Class<T> anonymousClass, T defaultValue) {
        if (anonymousClass == String.class) {
            return (T) mSharedPreferences.getString(key, (String) defaultValue);
        } else if (anonymousClass == Boolean.class) {
            return (T) Boolean.valueOf(mSharedPreferences.getBoolean(key, (Boolean) defaultValue));
        } else if (anonymousClass == Float.class) {
            return (T) Float.valueOf(mSharedPreferences.getFloat(key, (Float) defaultValue));
        } else if (anonymousClass == Integer.class) {
            return (T) Integer.valueOf(mSharedPreferences.getInt(key, (Integer) defaultValue));
        } else if (anonymousClass == Long.class) {
            return (T) Long.valueOf(mSharedPreferences.getLong(key, (Long) defaultValue));
        } else {
            return (T) App.self()
                    .getGSon()
                    .fromJson(mSharedPreferences.getString(key, ""), anonymousClass);
        }
    }

Thử test lại nào

Để test việc put và get một object thì bạn tạo một class như sau nhé
Employee.java
package com.quanda.sharedprefs.model;

public class Employee {

    private long mId;

    private String mName;

    public Employee(long id, String name) {
        mId = id;
        mName = name;
    }

    public long getId() {
        return mId;
    }

    public void setId(long id) {
        mId = id;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "mId=" + mId +
                ", mName='" + mName + '\'' +
                '}';
    }
}
Giờ thì chúng ta cùng thử chạy trong MainActivity xem kết quả như nào nhé các bạn
MainActivity.java
package com.quanda.sharedprefs.main;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.quanda.sharedprefs.R;
import com.quanda.sharedprefs.model.Employee;
import com.quanda.sharedprefs.utils.SharedPrefs;

public class MainActivity extends AppCompatActivity {

    public final String TAG = MainActivity.this.getClass().getName();
    public static final String FIRST_STAFF = "first_staff";
    public static final String SECOND_STAFF = "second_staff";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Employee employee = new Employee(1, "Nguyen Viet Manh");
        Employee employee2 = new Employee(2, "Do Xuan Duc");

        SharedPrefs.getInstance().put(FIRST_STAFF, employee);
        SharedPrefs.getInstance().put(SECOND_STAFF, employee2);

        Log.e(TAG, SharedPrefs.getInstance().get(FIRST_STAFF, Employee.class).toString());
        Log.e(TAG, SharedPrefs.getInstance().get(SECOND_STAFF, Employee.class).toString());
        
        Log.e(TAG, String.valueOf(SharedPrefs.getInstance().get("hello", Integer.class, 2)));
    }
}
Các bạn run project và cùng quan sát log trên Android Monitor
Android Monitor
com.quanda.sharedprefs E/com.quanda.sharedprefs.main.MainActivity: Employee{mId=1, mName='Nguyen Viet Manh'}
com.quanda.sharedprefs E/com.quanda.sharedprefs.main.MainActivity: Employee{mId=2, mName='Do Xuan Duc'}
com.quanda.sharedprefs E/com.quanda.sharedprefs.main.MainActivity: 2
Như vậy là chúng ta đã thành công trong việc put và get một object rồi.
Các bạn có thể tham khảo code tại đây https://github.com/dangquanuet/optimize-android-shared-preferences

Kết luận

Lần này mình đã giới thiệu đến các bạn một cách để tối ưu khi làm việc với SharedPreferences, tuy chỉ nhỏ gọn vậy thôi nhưng sẽ tiện dụng vô cùng. Nếu bạn biết cách nào tối ưu hơn thì hãy chia sẻ cho mọi người cùng biết nhé. Xin chào và hẹn gặp lại trong các bài tiếp theo.

Nhận xét

Bài đăng phổ biến từ blog này

Camera2 - Android

Ở bài viết này mình xin giới thiệu về cách sử dụng Camera2 trong android SDK 21. Với các lập trình viên android việc sử dụng Camera có rất nhiều trong ứng dụng: Camera Capture Images, Barcode - QR Code Reader, AR, Video Record,.... Nhiều ứng dụng chỉ ở tầng ứng dụng sử dụng thông qua  Intent  như vậy hệ thống tự động được gọi ở mức tối ưu nhất, nhưng cũng không ít ứng dụng cần can thiệp vào tầng  native  để xử lý Với  Camera   developer.android.com  đã  deprecate  nó đã không còn được sử dụng cơ bản trong các ứng dụng nữa vì rất nhiều nguyên nhân trong đó phải kể tới: tốn tài nguyên, thời gian capture khá chậm và đặc biệt phục vụ nhu cầu ngày càng cao của người dùng như 'Chụp ảnh liên tục, chụp nhiều ảnh và tự động lấy nét' thì  Camera không đáp ứng được Với  Camera2  đã đáp ứng được những thiếu xót trên ngoài ra việc customize cho ảnh là rất dễ dàng mang lại chất lượng cao ngoài ra việc sử dụng cũng không có nhiều thay ...

Sự khác nhau giữa let, apply, with, run và also trong Kotlin

Với những ai đã sử dụng Kotlin để phát triển ứng dụng, chắc hẳn đã không ít lần sử dụng các standard functions run, with, let, also và apply. Để hiểu và sử dụng thành thục chúng không phải là dễ. Và dưới đây là những điều đúc kết lại được. https://viblo.asia/p/su-khac-nhau-giua-let-apply-with-run-va-also-trong-kotlin-RQqKLNdml7z Scoping functions Có thể hiểu đơn giản, scoping function là phạm vi ảnh hưởng nhất định của một hàm. Nó là điều cốt lõi để phân biệt giữa các scoping functions: run, with, T.run, T.let, T.also và T.apply. Dưới đây là minh hoạ phạm vi của hàm run: fun test ( ) { var mood = "I am sad" run { val mood = "I am happy" println ( mood ) // I am happy } println ( mood ) // I am sad } Ở trên, ta có thể thấy rõ ràng trong phạm vi của hàm run, biến mood đã được định nghĩa lại trước khi in ra mà không làm ảnh hưởng tới phần khác của chương trình 3 attributes of scoping functions 1.Normal vs. extension fun...

TỰ ĐỘNG HUỶ ACTIVITY SAU KHI STARTACTIVITY

Trước giờ để huỷ một Activity khi bạn thường dùng hàm  finish()  đúng không nào? Không đi đâu xa là khi bạn Intent từ một Activity này sang Activity khác mà muốn huỷ luôn Activity đầu tiên luôn thì bạn sẽ dùng đoạn code y chang bên dưới chứ? Cơ chế của Activity là khi bạn chuyển từ một Activity này sáng Activity khác thì nó sẽ Activity đó vào stack, và khi back về thì Activity sẽ được hiện lên lại và chạy vào onResume(), nếu bạn chưa hiểu về  vòng đời của Activity  thì xem lại bài viết kèm video tại blog mình nhé, mình ví dụ khá chi tiết. Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); Đoạn code trên nghĩa là chuyển từ MainActivity sang LoginActivity và sau đó huỷ luôn MainActivity đúng không nào? Tuy nhiên đó không phải là cách duy nhất mà chúng ta làm đâu bởi Android hỗ trợ chúng ta một số thuộc tính mà bạn không phải dùng code Java để làm. Không lưu Activity vào stack Cũng logic như bài toán phí...