Use sharedpreferences in Android

Source: Internet
Author: User
Use sharedpreferences in Android

1. Use sharedpreferences 1

 
Protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); sharedpreferences mperferences = preferencemanager. getdefasharsharedpreferences (this); int counter = mperferences. getint ("counter", 1); textview mtextview = (textview) findviewbyid (R. id. showmssage); mtextview. settext ("counter is:" + counter); Editor meditor = mperferences. edit (); meditor. putint ("counter", ++ counter); meditor. commit ();}

Meditor. putint ("counter", ++ counter); writes the counter value to ++ counter, and finally submits.

Int counter = mperferences. getint ("counter", 1); obtains the value written to the couter. The default value is 1.

 

2. Create an SPF. xml file and write the data to the XML file. Finally, read the data in the XML file.

Protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); sharedpreferences = This. getsharedpreferences ("SPF", mode_private); Editor editor = sharedpreferences. edit (); Editor. putstring ("name", "James"); Editor. putint ("Age", 29); Editor. putboolean ("boy", true); Editor. commit (); log. I ("name", sharedpreferences. getstring ("name", "No Name"); log. I ("Age", integer. tostring (sharedpreferences. getint ("Age", 0); log. I ("boy", Boolean. tostring (sharedpreferences. getboolean ("boy", false )));}

Refer:

Sharedpreferences usage

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.