Android sharedpreferences General Read and write usage.

Source: Internet
Author: User

Android sharedpreferences is typically used for lightweight data storage, such as usernames and passwords.

1  Packagecom.lixu.testsharepreferences;2 3 Importandroid.app.Activity;4 ImportAndroid.content.Context;5 Importandroid.content.SharedPreferences;6 ImportAndroid.content.SharedPreferences.Editor;7 ImportAndroid.os.Bundle;8 ImportAndroid.widget.Toast;9 Ten  Public classMainactivityextendsActivity { One  A     Private Static FinalString user_name = "username"; -     Private Static FinalString USER_PWS = "USERPWS"; -     PrivateString name = "Name"; the  - @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); - writesharedpreferences (); + readsharedpreferences (); A  at     } -  -     //Context.mode_private This is to set access rights meaning that only the app can read and write the data inside -     //returns "No value" if no data is written in sharedpreferences; -     Private voidreadsharedpreferences () { -Sharedpreferences SP = This. Getsharedpreferences (NAME, context.mode_private); in  -String str1 = sp.getstring (user_name, "no value"); toString str2 = sp.getstring (USER_PWS, "no value"); +  -Toast.maketext (Getapplicationcontext (), "username is:" + str1, 1). Show (); the  *Toast.maketext (Getapplicationcontext (), "User password is:" + str2, 1). Show (); $ Panax Notoginseng     } -  the     Private voidwritesharedpreferences () { +Sharedpreferences SP = This. Getsharedpreferences (NAME, context.mode_private); A  theEditor EDT =Sp.edit (); +Edt.putstring (user_name, "Lixu"); -Edt.putstring (USER_PWS, "123456789"); $         //Submit $ edt.commit (); -  -     } the  -}

Operating effect:

Android sharedpreferences General Read and write 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.