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 got3.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 (); } }
4. remove the object from the Sharedpreferences
Public Static<T> T Getobjectfromshare (String shareName, class<t>clazz) { //Get Sharedpreferences InstancesSharedpreferences sharedpreferences =mcontext.getsharedpreferences (ShareName, activity.mode_private); //T is a generic type and varies according to ClazzT t =NULL; Try { //get all the data in the Sharedpreferences, and the data is stored in the map for key-value pairsmap<string,?> map =Sharedpreferences.getall (); //call the Getpublicfields method to get all the public properties in the ClazzList<field> Publicfields =Getpublicfields (Clazz); //If neither of them is empty. if(Map.size () >0 && publicfields.size () >0) { //instantiate the Tt =clazz.newinstance (); //Traverse all the key-value pairs in the map for(map.entry<string,?>Entry:map.entrySet ()) { //keys in the mapString key =Entry.getkey (); //values in MapObject value =Entry.getvalue (); //traverse all public properties in the Clazz for(Field field:publicfields) {//Get Property nameString name =Field.getname (); //If the property name is the same as the key if(Name.equalsignorecase (key)) {//equivalent to an attribute field assignment in the object T, valueField.set (t, value); Break; } } } } } Catch(Exception e) {e.printstacktrace (); } //after the entire traversal, the properties in our object also have values. returnT; }
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 log in the printed savedperson information source download
Android reflex to create a universal sharedpreferences