Android uses reflection to create a universal sharedpreferences that can store any object

Source: Internet
Author: User

We usually use Sharedpreferences to store some data that needs to be saved locally, but not stored in the database, generally we use it to store some user names, passwords and other data is very convenient, then if we want to store information there are 10 of several, We have to write 10 lines of repetitive code to put them in, take out the time also have to write 10 lines of code to remove them one by one, then there is no way you can just need a line of code to save them in, a line of code to take them out? The answer is yes, and in this article we'll show you how to do it through reflection.

1. encapsulate the data we want to save into an entity class Person.java where we use public to decorate

 Public classPerson {//String Type property name     PublicString name; //int type attribute age     Public intAge ; //Float Type Property height     Public floatheight; //whether the Boolean type property is married     Public Booleanismarried; //String Type property ID number     PublicString ID;}

2. through reflection, remove the attributes from the person class

 Public classSharedpreferencesutils {/*** Remove the properties that are decorated with the public modifier based on the incoming object *@paramClazz The bytecode file of the class to which the attribute is to be obtained *@returnA list table of all properties modified with Pulic*/     Public Static<T> list<field> Getpublicfields (class<?>clazz) {        if(Clazz.equals (Object).class)) {            return NULL; }        //List of properties used to store public decorations in Clazzlist<field> list =NewArraylist<field>(); //get all public-modified properties in Clazzfield[] Fields =Clazz.getfields (); //add fields to the list         for(inti=0; I<fields.length; i++) {List.add (fields[i]); }        returnlist; }

Let's start by testing if the property is removed, we'll add the following code to the Mainactivity.java to test it.

 Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //call the method we just wrote to get the properties in the person classlist<field> publicfields = sharedpreferencesutils.getpublicfields (person.class);  for(Field f:publicfields) {String name=F.getname (); LOG.I ("TAG", name+ "\ n"); }    }}
Let's take a look at the log print information we can see that the attributes in person we've got 3.Storing objects in a sharedpreferences
 Public Static voidPutobjecttoshare (String shareName, Object obj) {//Get Sharedpreferences InstancesSharedpreferences sharedpreferences =mcontext.getsharedpreferences (sharename,activity.mode_private); //Get editorEditor edit =Sharedpreferences.edit (); //clear previous old data before storing dataedit.clear (); //Call Commit data (here to clear the data)Edit.commit (); List<Field> Publicfields =Getpublicfields (Obj.getclass ());  for(Field f:publicfields) {String name=F.getname (); Try {                //get the type and value of the current property//type if it is a basic type, it will be boxed automaticallyObject type =f.get (obj); //judging various types, calling various types of put methods to store data in                if(TypeinstanceofString)                {edit.putstring (name, (String) type); }Else if(TypeinstanceofInteger)                {Edit.putint (name, (Integer) type); }Else if(TypeinstanceofFloat)                {Edit.putfloat (name, (Float) type); }Else if(TypeinstanceofLong)                {Edit.putlong (name, (Long) type); }Else if(TypeinstanceofBoolean)                {Edit.putboolean (name, (Boolean) type); }            } Catch(Exception e) {e.printstacktrace (); }            //call Commit, commit the dataEdit.commit (); }    }

5. Let's test and modify the code in the Mainacitvity.java.

 Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //instantiate a person instance, which is the object we want to store in SharedpreferencesPerson p =NewPerson ("Zhangsan", 23,175.0f,false, "001"); //save P to Sharedpreferences's "Zhangqi" nameSharedpreferencesutils.getinstance ( This). Putobjecttoshare ("Zhangqi", p);; //remove previously stored person instances from Sharedpreferences's "Zhangqi" namePerson Savedperson = Sharedpreferencesutils.getinstance ( This). Getobjectfromshare ("Zhangqi", person.class); LOG.E ("Zhangqi", "" "+savedperson.tostring ()); }}
Let's take a look at the Savedperson information printed in log

Android uses reflection to create a universal sharedpreferences that can store any object

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.