Andriod學習之SharedPreferences,andriod
SharedPreferences使用索引值對的方式來儲存資料,並支援多種不同類型的資料存放區。
1、介面布局
<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"> <!-- 展開第1列 -->
<TableRow>
<EditText
android:id="@+id/txtWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:hint="請輸入" />
<Button
android:id="@+id/btnWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="寫入" />
</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="讀取" />
</TableRow>
</TableLayout>
2、代碼
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和傳入0相同,表示只有當前應用程式才能對這個SharedPreferences檔案進行操作
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);
}
});
}
}
可以通過DDMS匯出產生的檔案。
檔案內容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">張三</string>
</map>