Sharedpreferences simple data storage, my understanding is similar to the Windows INI file
Can store many types, write a small example
Activity_main.xml
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:id= "@+id/linearlayout1"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.ssln.sharedpreferences.MainActivity" > <EditTextAndroid:id= "@+id/edittext1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:ems= "Ten" > <Requestfocus/> </EditText> <ButtonAndroid:id= "@+id/button2"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Write" /> <ButtonAndroid:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "read" /></LinearLayout>
Mainactivity.java
Packagecom.ssln.sharedpreferences;Importandroid.app.Activity;Importandroid.content.SharedPreferences;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton Btnwrite,btnread; PrivateEditText Edit; PrivateSharedpreferences sp; Private FinalString key= "Isrun"; Private FinalString name= "Sharedpreferences"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Btnwrite=(Button) Findviewbyid (R.id.button2); Btnread=(Button) Findviewbyid (R.id.button1); Edit=(EditText) Findviewbyid (R.ID.EDITTEXT1); //using activity.getpreferences can only be used in the corresponding activity (mainactivity)//sp=getpreferences (mode_private); //using Context.getsharedpreferences can be used by other components in the same applicationsp= This. Getsharedpreferences (NAME, mode_private); Btnread.setonclicklistener ( This); Btnwrite.setonclicklistener ( This); } @Override Public voidOnClick (View v) {//Read Content if(v==btnread) {String result=sp.getstring (KEY,NULL); if(result!=NULL) {Edit.settext (result); } Else{Toast.maketext ( This, "no corresponding value found", Toast.length_short). Show (); } } Else if(V==btnwrite)//Write Content { //writing and editing content requires the use of Sharedpreferences.editor objectsSharedpreferences.editor editor=Sp.edit (); Editor.putstring (KEY, Edit.gettext (). toString ()); //to commit after writing is completeEditor.commit (); Toast.maketext ( This, "Saved successfully", Toast.length_short). Show (); } }}
Android sharedpreferences simple data storage