A handy tool for Sharedpreferencesutils

Source: Internet
Author: User

Sharedpreferencesutils Storage Objects

Sharedpreferences can store basic types, which are not explained in more detail here. Here we mainly describe how to store objects.
Some of the common tool classes in my learning to optimize the Utils toolkit.
Some of the ways in which the Sharedpreferences store objects are used in Baidu Base64 turn, or turn into JSON type, into sharedpreferences, which is awkward to write. is not in line with my needs. Here's a new way to do it (I'm not sure, it should have been written early).

    • Read and write basic data types
    • Read/write JavaBean type
    • Read-write list<Javabean> Types
    • Read and write picture resources
1, read and write basic data types
/** * Store basic data type *@param context*@param key Key*@param data Value*/public static void SaveData (context context, string key, Object data) {String type = Data.getclass (). Getsimplena        Me (); Sharedpreferences sharedpreferences = context.getsharedpreferences (file_name, context. mode_private);//Read-write basic data types are in a specific file, with the package name of the software as the file Name Editor editor = Sharedpreferences.edit ();if("Integer". Equals (type) {//Note here is an Integer object, with Editor.putint (key, (Integer) data); }Else if("Boolean". Equals (Type) {Editor.putboolean (key, (Boolean) data); }Else if("String". Equals (Type) {editor.putstring (key, (String) data); }Else if("Float". Equals (Type) {Editor.putfloat (key, (Float) data); }Else if("Long". Equals (Type) {Editor.putlong (key, (Long) data);    } editor.commit (); }/** * Read basic data type *@param context*@param key Key*@param defvalue Returns the default value when no value is taken*@return*/public static object GetData (context context, string key, Object Defvalue) {String type = Defvalue.getclass (        ). Getsimplename (); Sharedpreferences sharedpreferences = context.getsharedpreferences (file_name, context.  Mode_private); Defvalue is the default value and returns it if the data is not currently availableif("Integer". Equals (type)) {returnSharedpreferences.getint (Key, (Integer) defvalue); }Else if("Boolean". Equals (type)) {returnSharedpreferences.getboolean (Key, (Boolean) defvalue); }Else if("String". Equals (type)) {returnSharedpreferences.getstring (Key, (String) defvalue); }Else if("Float". Equals (type)) {returnSharedpreferences.getfloat (Key, (Float) defvalue); }Else if("Long". Equals (type)) {returnSharedpreferences.getlong (Key, (Long) defvalue); }returnNull }

The basic data types that are commonly used are stored in a specific file, and are easily and quickly obtained. (Ps,string is not a basic data type)

Read/write JavaBean type

Advance preparation
JavaBean is serialized and needs to inherit the serializable interface to implement Serialversionuid.
1. Determine if the processing is the individual data type

 Private Static Boolean IsObject(Class<?> clazz) {returnClazz! =NULL&&!issingle (clazz) &&!isarray (clazz) &&!iscollection (clazz) &&!ismap (clazz); }Private Static Boolean Issingle(Class<?> clazz) {returnIsboolean (clazz) | | Isnumber (clazz) | |    Isstring (Clazz); } Public Static Boolean Isboolean(Class<?> clazz) {returnClazz! =NULL&& (Boolean.TYPE.isAssignableFrom (clazz) | |    Boolean.class.isAssignableFrom (Clazz)); } Public Static Boolean Isnumber(Class<?> clazz) {returnClazz! =NULL&& (Byte.TYPE.isAssignableFrom (clazz) | | Short.TYPE.isAssignableFrom (clazz) | | Integer.TYPE.isAssignableFrom (clazz) | | Long.TYPE.isAssignableFrom (clazz) | | Float.TYPE.isAssignableFrom (clazz) | | Double.TYPE.isAssignableFrom (clazz) | |    Number.class.isAssignableFrom (Clazz)); } Public Static Boolean isstring(Class<?> clazz) {returnClazz! =NULL&& (String.class.isAssignableFrom (clazz) | | Character.TYPE.isAssignableFrom (clazz) | |    Character.class.isAssignableFrom (Clazz)); } Public Static Boolean IsArray(Class<?> clazz) {returnClazz! =NULL&& Clazz.isarray (); } Public Static Boolean iscollection(Class<?> clazz) {returnClazz! =NULL&& Collection.class.isAssignableFrom (Clazz); } Public Static Boolean IsMap(Class<?> clazz) {returnClazz! =NULL&& Map.class.isAssignableFrom (Clazz); }Private Static Boolean Isparcelablecreator(Field field) {returnModifier.tostring (Field.getmodifiers ()). Equals ("public static final") &&"CREATOR". Equals (Field.getname ()); }

2, inserting data

  Public Static void SetObject(Context context, Object O) {field[] fields = O.getclass (). Getdeclaredfields ();//Get Properties of all claimsSharedpreferences sp = context.getsharedpreferences (O.getclass (). GetName (),0);//change stored file name to JavaBean package name + category nameSharedpreferences.editor Editor = Sp.edit (); for(inti =0; i < fields.length; ++i) {if(!isparcelablecreator (Fields[i])) {Class type = Fields[i].gettype ();//Type class Java.lang.classString name = Fields[i].getname ();//Name IDObject e;if(Issingle (type)) {Try{if(Type! = Character.type &&!type.equals (string.class)) {if(!type.equals (Integer.type) &&!type.equals (Short.class)) {if(Type.equals (Double.type))                                            {Editor.putlong (name, Double.doubletolongbits (fields[i) . getdouble (o)));//The value of double type is deposited}Else if(Type.equals (Float.type)) {editor.putfloat (name, Fields[i].getfloat (o));//The value of float type is deposited}Else if(Type.equals (Long.type) &&!name.equals ("Serialversionuid") {Editor.putlong (name, Fields[i].getlong (o));//Type a Long value into}Else if(Type.equals (Boolean.type)) {Editor.putboolean (name, Fields[i].getboolean (o));//Type a Boolean value into}                            }Else{editor.putint (name, Fields[i].getint (o));//The value of int type is deposited}                        }Else{e = Fields[i].get (o);//The value of string type is depositedEditor.putstring (Name,NULL= = e?NULL: E.tostring ()); }                    }Catch(Exception var14) {                    }                    }Else if(IsObject (type)) {Try{e = Fields[i].get (o);if(NULL! = e) {setobject (context, E); }Else{Try{setobject (context, Fields[i].getclass (). newinstance ());//Run again}Catch(Instantiationexception Var11) {                                }                            }                        }Catch(Exception var12) {                        }                    }Else{Try{e = Fields[i].get (o);//Turn into JSON insert}Catch(Illegalaccessexception E1)                    {E1.printstacktrace ();    }}}} editor.apply (); } Public Static<T> TGetObject(context context, class<t> Clazz) {Object o =NULL;Try{o = Clazz.newinstance (); }Catch(Instantiationexception e) {E.printstacktrace ();return(T) O; }Catch(Illegalaccessexception e) {E.printstacktrace ();return(T) O;        } field[] fields = Clazz.getdeclaredfields (); Sharedpreferences sp = context.getsharedpreferences (Clazz.getname (),0); for(inti =0; i < fields.length; ++i) {if(!isparcelablecreator (Fields[i]))                {Class type = Fields[i].gettype ();                String name = Fields[i].getname (); String o_1;if(Issingle (type)) {Try{fields[i].setaccessible (true);if(Type! = Character.type &&!type.equals (string.class)) {if(!type.equals (Integer.type) &&!type.equals (Short.class)) {if(Type.equals (Double.type)) {fields[i].setdouble (O, double.longbitstodouble (Sp.getlong (name,0L))); }Else if(Type.equals (Float.type)) {fields[i].setfloat (O, sp.getfloat (name,0.0F)); }Else if(Type.equals (Long.type)) {Fields[i].setlong (O, Sp.getlong (name,0L)); }Else if(Type.equals (Boolean.type)) {Fields[i].setboolean (O, Sp.getboolean (name,false)); }                            }Else{Fields[i].setint (O, sp.getint (name,0)); }                        }Else{o_1 = sp.getstring (name, (String)NULL);if(NULL! = o_1) {fields[i].set (o, o_1); }                        }                    }Catch(Exception e) {                    }                }Else if(IsObject (type)) {Object Tempvalue = getObject (context, Fields[i].gettype ());if(NULL! = Tempvalue) {fields[i].setaccessible (true);Try{Fields[i].set (o, Tempvalue); }Catch(Exception e) {                        }                     }                }Else{//json Data Parsing}            }        }return(T) O; }

The main idea is to traverse all of the JavaBean property objects, take them out, and deposit them into the XML file by type.
When taken out, it is also converted into a deposit form, which facilitates

Read/write list< Javabean>

For list<JavaBean, it is not suitable to use the above method, generally not very likely to save this data, the amount of data is larger. If you have this requirement, you can convert list<javabean> into JSON form and then save it in an XML file. About JavaBean data into JSON will be described in another article.

Read and write picture resources

The so-called reading and writing pictures, personal feeling is not useful, first talk about ideas. In fact, it is also very simple, is through the base64 output into a string.
The code:

 Private void savebitmaptosharedpreferences(Context context,string key,bitmap Bitmap) {///First step: Compress bitmap into byte array output stream BytearrayoutputstreamBytearrayoutputstream bytearrayoutputstream=NewBytearrayoutputstream (); Bitmap.compress (Compressformat.png, the, Bytearrayoutputstream);///Step two: Convert data from a byte array output stream to a string using Base64        byte[] Bytearray=bytearrayoutputstream.tobytearray (); String imagestring=NewString (Base64.encodetostring (ByteArray, Base64.default));//Step Three: Keep the string to SharedpreferencesSharedpreferences sharedpreferences=context.getsharedpreferences (file_name, context.mode_private);          Editor Editor=sharedpreferences.edit ();          Editor.putstring (key, imagestring);      Editor.commit (); }PrivateBitmapgetbitmapfromsharedpreferences(context context, String key, Object defvalue) {sharedpreferences sharedpreferences=getsharedpreferences (file_name, context.mode_private);//First step: Take out the string form of the bitmapString imagestring=context.sharedpreferences.getstring (Key,defvalue);///Step Two: Convert a string to Bytearrayinputstream using Base64        byte[] Bytearray=base64.decode (imagestring, Base64.default); Bytearrayinputstream bytearrayinputstream=NewBytearrayinputstream (ByteArray);//Step three: Generate Bitmap with BytearrayinputstreamBitmap Bitmap=bitmapfactory.decodestream (Bytearrayinputstream);returnBitmap }
End

A brief description of the use of the next sharedpreferences, after all, as a few of the main data storage in Android, proficiency is still very necessary.

A handy tool for Sharedpreferencesutils

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.