Shared storage of Android learning notes data sharedpreferences

Source: Internet
Author: User
Tags save file

(1) Layout file, a simple login file;

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <textview android:id=" @+id/textview1 "android:layout_width=" Wrap_content "an droid:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparenttop= "true "Android:layout_marginleft=" 22DP "android:layout_margintop=" 22DP "android:text=" User name: "/> <e Dittext android:id= "@+id/edittext1" android:layout_width= "wrap_content" android:layout_height= "Wrap_c Ontent "Android:layout_alignbaseline=" @+id/teXtView1 "android:layout_alignbottom=" @+id/textview1 "android:layout_torightof=" @+id/textview1 "Androi d:ems= "Ten"/> <textview android:id= "@+id/textview2" android:layout_width= "Wrap_content" Android oid:layout_height= "Wrap_content" android:layout_alignright= "@+id/textview1" android:layout_below= "@+id/editT Ext1 "android:layout_margintop=" 17DP "android:text=" Password: "/> <edittext android:id=" @+id/editt Ext2 "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layout_alignle ft= "@+id/edittext1" android:layout_below= "@+id/edittext1" android:ems= "android:inputtype=" TextPas Sword "> <requestfocus/> </EditText> <button android:id=" @+id/button2 "Andro        Id:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/checkBox1" Android:layout_marginleft= "34DP" android:layout_margintop= "32DP" android:layout_torightof= "@+id/button1" android:text= "fetch "/> <checkbox android:id=" @+id/checkbox1 "android:layout_width=" Wrap_content "Android:layo"        ut_height= "Wrap_content" android:layout_alignleft= "@+id/textview1" android:layout_below= "@+id/editText2"        android:layout_margintop= "22DP" android:text= "Remember user name"/> <button android:id= "@+id/button1" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_alignbaseline= "@+i D/button2 "android:layout_alignbottom=" @+id/button2 "android:layout_alignleft=" @+id/edittext2 "Androi d:text= "Login"/> <checkbox android:id= "@+id/checkbox2" android:layout_width= "Wrap_content" and roid:layout_height= "Wrap_content" android:layout_alignbaseline= "@+id/checkbox1" android:layout_alignbottom= " @+id/checkbox1 "Android:layout_marginleft= "14DP" android:layout_torightof= "@+id/button1" android:text= "Mute Login"/></Relati Velayout>

(2) directory structure:


(3) Sharedpreferences Tool class Loginservice.java

Package Com.lc.data_storage_share.sharepreference;import Java.util.map;import Android.content.context;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;public class LoginService { Private context context; Context Public Loginservice (context context) {This.context = context;} /* Save login Information */public boolean saveloginmsg (string name, String password) {Boolean flag = false;//do not add suffix, the system is automatically saved in. xml format//This Login is the file name to be stored sharedpreferences preferences = context.getsharedpreferences ("Login", context. Mode_private + context. Mode_append); Editor editor = Preferences.edit (); editor.putstring ("name", name), editor.putstring ("password", password); flag = Editor.commit (); return flag;} /* * Save File */public boolean savesharepreference (String filename, map<string, object> Map) {Boolean flag = false; Sharedpreferences preferences = context.getsharedpreferences (filename,context.mode_private);/* * Use editor when saving data Editor editor = Preferences.edit (); for (map.entry<string, OBJECT> Entry:map.entrySet ()) {String key = Entry.getkey (); Object object = Entry.getvalue (); if (Object instanceof Boolean) {Boolean new_name = (Boolean) Object;editor.putboolean (key, new_name);} else if (object instanceof Integer) {integer integer = (integer) object;editor.putint (key, Integer);} else if (Object inst anceof float) {float F = (float) object;editor.putfloat (key, f);} else if (object instanceof Long) {Long L = (long) object ; Editor.putlong (key, L);} else if (object instanceof String) {string s = (string) object;editor.putstring (key, s);}} Flag = Editor.commit (); return flag;} /* * Read file */public map<string,?> getsharepreference (String filename) {map<string,?> Map = null; Sharedpreferences preferences = context.getsharedpreferences (filename,context.mode_private);/* * Read data when hungry only need to access */ Map = Preferences.getall (); return map;}}

(3) Mainactivity.java

Package Com.lc.data_storage_share;import Java.util.hashmap;import Java.util.map;import Com.example.data_storage_ Share. R;import Com.lc.data_storage_share.sharepreference.loginservice;import Android.os.bundle;import Android.app.activity;import Android.view.menu;import Android.view.view;import Android.view.View.OnClickListener; Import android.widget.button;import android.widget.checkbox;import android.widget.edittext;/* * unit tests need to be in the manifest file */ public class Mainactivity extends Activity {private button button1;//login private button button2;//Cancel private EditText Editt Ext1, edittext2;private checkbox checkbox1;//Remember password private CheckBox checkBox2; Mute Login Private Loginservice service; map<string,?> map = null, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); button1 = (Button) This.findviewbyid (R.id.button1); Button2 = (Button) This.findviewbyid (r.id.button2); editText1 = (EditText) This.findviewbyid (r.id.edittext1); editText2 = (EditText) This.findviewbyid (r.id.edittext2); checkBox1 = (CheckBox) This.findviewbyid (r.id.checkbox1); CheckBox2 = (CheckBox) This.findviewbyid (r.id.checkbox2); service = new Loginservice (this); map = Service.getsharepreference ("Login"), if (map! = null &&!map.isempty ()) {Edittext1.settext (Map.get ("username" ). ToString ()), Checkbox1.setchecked ((Boolean) Map.get ("Isname")), Checkbox2.setchecked ((Boolean) Map.get ("Isquiet" ));} Button1.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubif (Edittext1.gettext (). toString (). Trim (). Equals ("admin")) {map<string, object> map1 = new hashmap< String, object> (), if (checkbox1.ischecked ()) {Map1.put ("username", Edittext1.gettext (). toString (). Trim ());} else {map1.put ("username", "");} Map1.put ("Isname", checkbox1.ischecked ()), Map1.put ("Isquiet", checkbox2.ischecked ()); service.savesharepreference ("Login", MAP1);}}); @Overridepublic Boolean Oncreateoptionsmenu (Menumenu) {//Inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu ); return true;}}

(4) Test class:

Package Com.lc.data_storage_share;import Java.util.hashmap;import Java.util.map;import Android.test.androidtestcase;import Android.util.log;import Com.lc.data_storage_ Share.sharepreference.loginservice;public class MyTest extends Androidtestcase {private final String TAG = "MyTest"; Public MyTest () {//TODO auto-generated constructor stub}/* * Login */public void Save () {Loginservice service = new Loginser Vice (GetContext ()); Boolean flag = Service.saveloginmsg ("admin", "123"); LOG.I (TAG, "-->>" + flag);} /* * Save file */public void SaveFile () {Loginservice service = new Loginservice (GetContext ()); map<string, object> map = new hashmap<string, object> (); Map.put ("Name", "Jack"); Map.put ("Age", at a); map.put ("Salary", 23000.0f); Map.put ("id", 1256423132l); Map.put ("Ismanager", true); Boolean flag = Service.savesharepreference ("MSG", map); LOG.I (TAG, "-->>" + flag);} /* * Read file */public void ReadFile () {Loginservice service = new Loginservice (GetContext ()); map<string,?> map = SerVice.getsharepreference ("msg"); LOG.I (TAG, "-->>" + map.get ("name")); LOG.I (TAG, "-->>" + map.get ("age")); LOG.I (TAG, "-->>" + map.get ("salary")); LOG.I (TAG, "-->>" + map.get ("Ismanager")); LOG.I (TAG, "-->>" + map.get ("id"));}}

How to add JUnit test units:

1. Add the following in the manifest file:


2. Add in Application:


3. Test class mytest to inherit Androidtestcase


(5) As a result, the next time you log in will remember the user name







Shared storage of Android learning notes data sharedpreferences

Related Article

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.