Android uses reflection to create a universal sharedpreferences that can store no matter what object

Source: Internet
Author: User

We usually use Sharedpreferences to store some of the needs to be saved locally. But not some data stored in the database. Generally we use it to store some username,password and other data is very convenient, then assume that we want to store information there are 10 of several. We have to write 10 lines of repeated code to put them in. When you take it out, you have to write 10 lines of code to take them out of one piece, so is there any way to save them in a single line of code and take them out of the line? The answer is yes, and this article shows you how to do it through reflection.

1. encapsulate the data we want to save as an entity class Person.java attributes we all use public to decorate


2.Through reflection. Take a property out of the person class let's try to test the property if it has been taken out, we add the following code to the Mainactivity.java for example. Let's take a look at the log printing information we can see that the attributes in the person we've got.
3.Storing objects in a sharedpreferences
4.Remove an object from the Sharedpreferences
5.Let's test it, change the code in Mainacitvity.java. Let's take a look at the Savedperson information printed in log
Source code Download

Android uses reflection to create a universal sharedpreferences that can store no matter what object

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.