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

Get Current location using FusedLocationProviderClient in Android

Hello to coders, Previously we have taught you  how you get current location using GPS/Network Provider . Then android has revealed  FusedLocationProviderClient  under  GoogleApi . FusedLocationProviderClient is for interacting with the location using fused location provider. ( NOTE :   To use this feature, GPS must be turned on your device. For manually ask the user to turn on GPS, please check  next article ) So let’s get started for the tutorial for getting the current location. First, add a dependency for location by play services: implementation 'com.google.android.gms:play-services-location:15.0.1' Then define FusedLocationProviderClient: private FusedLocationProviderClient mFusedLocationClient; private TextView txtLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_main ); this.txtLocation = (TextView) findViewById(R.id. txtLocat...

NHỮNG WIDGET THƯỜNG DÙNG TRONG FLUTTER

 https://baoflutter.com/nhung-widget-thuong-dung-trong-flutter/ Trong bài viết trước về  cách xây dựng màn hình ứng dụng Flutter , các bạn biết rằng các màn hình ứng dụng được tạo ra bởi các widget ghép lại với nhau. Vì vậy việc hiểu và sử dụng các Widget là rất quan trọng. Vì vậy trong bài viết này, tôi sẽ giới thiệu cho các bạn về những widget quan trọng trong Flutter. Hầu hết các Widget đều có các phần sau đây: + Đặc tính của Widget như : color, theme, height, weight, decoration, onTap, onPressed + Liên kết với các Widget khác với từ khoá: child, children, home hoặc body Ví dụ : 1 2 3 4 5 6 Container ( color : Colors . blue , height : 300 , weight : 300 , child : Text ( "Widget con" ) , ) Khi làm một số App cơ bản, bạn sẽ nắm chắc được cách sử dụng các Widget hay dùng. MaterialApp – Là widget rất liện lợi, cung cấp các widget cho việc xây dựng ứng dụng sử dụng thư viện Material Design UI của google. – Widget này được sử dụng trong hàm build đầu tiên của hầu hết các ứn...

Understanding the Android Application Class

Overview The  Application  class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created. This class is primarily used for initialization of global state before the first  Activity  is displayed. Note that custom  Application  objects should be used carefully and are often  not needed at all . Custom Application Classes In many apps, there's no need to work with an application class directly. However, there are a few acceptable uses of a custom application class: Specialized tasks that need to run before the creation of your first activity Global initialization that needs to be shared across all components (crash reporting, persistence) Static methods for easy access to static immutable data such as a shared network cl...