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.