Well, it's just a SharedPreferences tool class

In Android development, there will be a variety of tool classes to help us develop projects quickly. This time, we will implement the tool class of SharedPreference

Buddha once said:

//
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                           O\  =  /O
//                        ____/`---'\____
//                      .'  \\|     |//  `.
//                     /  \\|||  :  |||//  \
//                    /  _||||| -:- |||||-  \
//                    |   | \\\  -  /// |   |
//                    | \_|  ''\---/''  |   |
//                    \  .-\__  `-`  ___/-. /
//                  ___`. .'  /--.--\  `. . __
//               ."" '<  `.___\_<|>_/___.'  >'"".
//              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//              \  \ `-.   \_ __\ /__ _/   .-` /  /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                      Buddha bless never BUG

//           Buddha said:
//                  Office building office, office programmer;
//                  Programmers write programs and exchange them for drinks.
//                  Drunk only sit on the Internet, drunk to sleep under the net;
//                  Drunk and sober day after day, the Internet next year after year.
//                  I wish I didn't bow to my boss in the computer room;
//                  Mercedes Benz and BMW are expensive, and bus self programmers.
//                  Others laugh at my madness, I laugh at my life too cheap;
//                  I don't see beautiful girls all over the street. Which one is the programmer?
//

Alas, in fact, being a programmer is very tired. Buddha, help me!

Well, the reference tool class is very easy to use, after practice!

public class SharedPreferencesUtils {
    /**
     * File name saved in mobile phone
     */
    public static final String FILE_NAME = "share_data";

    /**
     * For the method of saving data, we need to get the specific type of saving data, and then call different saving methods according to the type
     *
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * We get the way to save the data. We get the specific type of the data saved according to the default value, and then call the relative method to get the value.
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * Remove the corresponding value of a key value
     *
     * @param context
     * @param key
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * Clear all data
     *
     * @param context
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * Query whether a key already exists
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * Return all key value pairs
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * Create a compatible class that resolves the SharedPreferencesCompat.apply method
     *
     * @author zhy
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * Reflection search method for apply
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * Use apply if found, otherwise use commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }
}

The use of SharedPreference is encapsulated and put, get, remove, clear and other methods are published;

Note that all the commit operations are replaced by SharedPreferencesCompat.apply. The purpose is to use apply instead of commit as much as possible

First of all, why? Because the commit method is synchronous, and many of our commit operations are in UI threads, after all, IO operations, asynchronous as possible;

So we use apply instead of write asynchronously;

But apply is the new API equivalent to commit. For better compatibility, we have made adaptation;

Daniel, you know, I stand on the shoulders of giants!

10 common tool classes of Android rapid development series

Tags: Android Mobile

Posted on Wed, 01 Apr 2020 20:39:37 -0700 by shinagawa