SharedPreferences for learning Andriod, andriod
SharedPreferences uses key-value pairs to store data and supports different types of data storage.
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 1st columns -->
<TableRow>
<EditText
Android: id = "@ + id/txtWrite"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = ""
Android: hint = "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.txt Write );
String string = txtEditText. getText (). toString ();
// MODE_PRIVATE is the same as 0, indicating that only the current application can operate on the 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.txt Read );
TextView. setText (string );
}
});
}
}
You can use DDMS to export the generated files.
The file content is as follows:
<? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?>
<Map>
<String name = "name"> Michael </string>
</Map>