Android Common Tool class Sputil, you can modify the default SP file path

Source: Internet
Author: User

Reference:

1. Change the sharedpreferences storage path using the Java reflection mechanism Singleton1900

2. Android Rapid Development series 10 commonly used tools class Hongyang

Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.content.ContextWrapper;Importandroid.content.SharedPreferences;ImportJava.io.File;ImportJava.lang.reflect.Field;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;ImportJava.util.Map; Public classSputil {/**the path of the SP file is allowed to be modified in the debug environment*/     Public Static Final BooleanIsdebug =true; /**to modify the path of a future SP file*/     Public Static FinalString File_path = "/sdcard/sp_file_path"; /*** Save Data * *@paramContext *@paramFileName file name, ". xml" is not required *@paramKeyName *@paramvalue*/     Public Static voidput (context context, string fileName, String keyName, Object value) {sharedpreferences.editor Editor=getsharedpreferences (context, FileName). Edit (); if(ValueinstanceofString)        {editor.putstring (KeyName, (String) value); } Else if(ValueinstanceofInteger)        {Editor.putint (KeyName, (Integer) value); } Else if(ValueinstanceofBoolean)        {Editor.putboolean (KeyName, (Boolean) value); } Else if(ValueinstanceofFloat)        {Editor.putfloat (KeyName, (Float) value); } Else if(ValueinstanceofLong)        {Editor.putlong (KeyName, (Long) value); } Else{editor.putstring (KeyName, value.tostring ());    } sharedpreferencescompat.apply (editor); }    /*** Get Data * *@paramContext *@paramFileName *@paramKeyName *@paramDefaultValue Default Value *@return     */     Public StaticObject Get (context context, string fileName, String keyName, Object defaultvalue) {sharedpreferences SP=getsharedpreferences (context, fileName); if(DefaultValueinstanceofString) {            returnsp.getstring (KeyName, (String) defaultvalue); } Else if(DefaultValueinstanceofInteger) {            returnSp.getint (KeyName, (Integer) defaultvalue); } Else if(DefaultValueinstanceofBoolean) {            returnSp.getboolean (KeyName, (Boolean) defaultvalue); } Else if(DefaultValueinstanceofFloat) {            returnsp.getfloat (KeyName, (Float) defaultvalue); } Else if(DefaultValueinstanceofLong) {            returnSp.getlong (KeyName, (Long) defaultvalue); }        return NULL; }    /*** Remove the value corresponding to a key value * *@paramContext *@paramFileName *@paramKeyName*/     Public Static voidRemove (context context, string fileName, String keyName) {Sharedpreferences.editor Editor=getsharedpreferences (context, FileName). Edit ();        Editor.remove (KeyName);    Sharedpreferencescompat.apply (editor); }    /**Clear All data*/     Public Static voidClear (Context context, String FileName) {sharedpreferences.editor Editor=getsharedpreferences (context, FileName). Edit ();        Editor.clear ();    Sharedpreferencescompat.apply (editor); }    /*** Query If a key already exists * *@paramContext *@paramKeyName *@return     */     Public Static Booleancontains (context context, string fileName, String keyName) {returngetsharedpreferences (context, FileName). Contains (keyName); }    /**returns all key-value pairs*/     Public StaticMap<string,?>GetAll (Context context, String FileName) {returngetsharedpreferences (context, FileName). GetAll (); }    /**Create a compatible class that resolves the Sharedpreferencescompat.apply method*/    Private Static classSharedpreferencescompat {Private Static FinalMethod Sapplymethod =Findapplymethod (); /**How reflection finds an apply*/@SuppressWarnings ({"Unchecked", "Rawtypes"})        Private StaticMethod Findapplymethod () {Try{Class Clz= Sharedpreferences.editor.class; returnClz.getmethod ("Apply"); } Catch(Nosuchmethodexception e) {}return NULL; }        /**if found, use apply to execute, otherwise commit is used*/         Public Static voidapply (Sharedpreferences.editor Editor) {Try {                if(Sapplymethod! =NULL) {Sapplymethod.invoke (editor); return; }            } Catch(IllegalArgumentException e) {}Catch(Illegalaccessexception e) {}Catch(InvocationTargetException e) {} editor.commit (); }    }    /**     * @paramContext *@paramFileName *@returnIsdebug = return modified path (path does not exist automatically created) after sharedpreferences:%file_path%/%filename%.xml<br/> *!isdebug = return to the default path of S Haredpreferences:/data/data/%package_name%/shared_prefs/%filename%.xml*/    Private Staticsharedpreferences getsharedpreferences (context context, String FileName) {if(isdebug) {Try {                //gets the mbase variable in the Contextwrapper object. The variable holds the Contextimpl objectField field = Contextwrapper.class. Getdeclaredfield ("Mbase"); Field.setaccessible (true); //Get mbase variableObject obj =Field.get (context); //gets the Contextimpl. Mpreferencesdir variable that holds the save path to the data filefield = Obj.getclass (). Getdeclaredfield ("Mpreferencesdir"); Field.setaccessible (true); //Create a custom pathFile File =NewFile (File_path); //Modifying the value of a Mpreferencesdir variablefield.set (obj, file); //returns the sharedpreferences after the modified path:%file_path%/%filename%.xml                returncontext.getsharedpreferences (FileName, activity.mode_private); } Catch(nosuchfieldexception e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); }        }        //return to sharedpreferences under the default path:/data/data/%package_name%/shared_prefs/%filename%.xml        returncontext.getsharedpreferences (FileName, context.mode_private); }}

Android Common Tool class Sputil, you can modify the default SP file path

Related Article

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.