Implementation of a SharedPreferences tool class, sharedpreferences

Source: Internet
Author: User

Implementation of a SharedPreferences tool class, sharedpreferences

In Android development, there will be a variety of tool classes to help us quickly develop projects, this implementation of SharedPreference tool class

Buddha once said:

/// _ OoOoo _ // o8888888o // 88 ". "88 // (|-_-|) // O \=/O //____/'---'\____//. '\\| | //'. /// \\||||||/////// _ ||||||| -: -|-\/| \-/| \ _ | ''\ ---/'' | //\. -\__'-'___/-. ///___'.. '/--. --\'.. __//. "" '<'. ___ \_< |> _/___. '> '"". // | :'-\'.; '\_/';. '/-': | //\\'-. \___\/___/. -'// ====== '-. ____'-. ___\_____/___. -'____. -'= //' = --- = '// ^ ^/Buddha bless forever no BUG // fo Yue: // The office room and the programmer in the office room; // The programmer writes the program and exchanges the wine with the program. // You can only sit online and sleep when you are drunk. // you can wake up And get online for the next year. // I hope that the old computer room will not bow to the boss before it; // Mercedes Benz is interesting, and the bus programmers themselves. // When others laugh at me, I laugh at myself, and my life is so cheap. // No pretty girl in the street, which is the programmer? //

Alas, actually, being a programmer is so tired and tired that Buddha can help me!

Well, the reference tool class is very useful and has been practiced!

Public class SharedPreferencesUtils {/*** file name saved in the mobile phone */public static final String FILE_NAME = "share_data";/*** how to save data, we need to get the specific type of data to be saved, and then call Different Storage Methods Based on 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);}/*** to obtain the method for saving data. We can obtain the specific type of data to be saved Based on the default value, then call the method to obtain 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 value corresponding to 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);}/*** returns all key-value pairs ** @ param context * @ return */public static Map
 
  
GetAll (Context context) {SharedPreferences sp = context. getSharedPreferences (FILE_NAME, Context. MODE_PRIVATE); return sp. getAll ();}/*** creates a solution for SharedPreferencesCompat. A compatible class of the apply Method ** @ author zhy */private static class SharedPreferencesCompat {private static final Method sApplyMethod = findApplyMethod (); /*** reflect the apply method ** @ return */@ SuppressWarnings ({"unchecked", "rawtypes"}) private st Atic 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 ();}}}
 

Recommended encapsulation for SharedPreference usage, and release put, get, remove, clear, and other methods;

Note that all the commit operations in IT use SharedPreferencesCompat. apply to replace commit.

First of all, let's explain why, because the commit method is synchronous, and many of our commit operations are in the UI thread. After all, they are IO operations, and they are as Asynchronous as possible;

So we use apply for replacement, and apply for asynchronous writing;

But apply is equivalent to commit, which is a new API. We have adapted it for better compatibility;

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.