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


2.Take a property out of the person class by reflection let's test the property if it is removed, and we'll add the following code to the Mainactivity.java to test it. We can see the information we have about the log print, and we've got the property in person.
3.Storing objects in a sharedpreferences
4.Remove an object from the Sharedpreferences
5.Let's test it, modify the code in Mainacitvity.java. Let's take a look at the Savedperson information printed in log
SOURCE download

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android uses reflection to create a universal sharedpreferences that can store any 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.