Sharedpreferences uses key-value pairs to store data and supports many different types of data stores.
1. Interface layout
<tablelayout 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"
Tools:context= ". Mainactivity "
android:stretchcolumns= "0" > <!--stretch 1th--
<TableRow>
<edittext
Android:id= "@+id/txtwrite"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:text= ""
android:hint= "Please enter"/>
<button
Android:id= "@+id/btnwrite"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Write"/>
</TableRow>
<TableRow>
<textview
Android:id= "@+id/txtread"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= ""/>
<button
Android:id= "@+id/btnread"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "read"/>
</TableRow>
</TableLayout>
2. Code
public class Mainactivity extends Activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Button Btnwrite = (button) Findviewbyid (id.btnwrite);
Btnwrite.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
EditText Txtedittext = (EditText) Findviewbyid (r.id.txtwrite);
String string = Txtedittext.gettext (). toString ();
Mode_private and incoming 0 are the same, indicating that only the current application can operate on this sharedpreferences file
Sharedpreferences.editor Editor = getsharedpreferences ("Data", Mode_private). Edit ();
Editor.putstring ("name", string);
Editor.commit ();
}
});
Button Btnread = (button) Findviewbyid (Id.btnread);
Btnread.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
Sharedpreferences sharedpreferences = getsharedpreferences ("Data", mode_private);
String string = sharedpreferences.getstring ("name", "");
TextView TextView = (TextView) Findviewbyid (R.id.txtread);
Textview.settext (string);
}
});
}
}
The resulting file can be exported through DDMS.
The contents of the file are as follows:
<?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?>
<map>
<string name= "Name" > Zhang San </string>
</map>
The Sharedpreferences of Andriod learning