Androidアプリ入門 No.40 Preferenceの基本 単純なデータの保管
Preferenceの基本
単純なデータの保管
Androidでデータを保存するにはいくつかの方法があるが、一番簡単に扱えるのがPreferenceである。PreferenceはJavaのMapのようなデータ構造でデータを保管する。つまり、キーに対する値と言う形でデータを保管する。
単純な例でデータが保管されていることを確認する。まずは、main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/editText" android:singleLine="true" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:text="保存" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.javaは以下。
package sample.at; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText editText; private Button button; private SharedPreferences pref; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText) findViewById(R.id.editText); pref = getPreferences(MODE_PRIVATE); editText.setText(pref.getString("test", "")); button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Editor editor = pref.edit(); editor.putString("test", editText.getText().toString()); editor.commit(); Toast.makeText(getApplicationContext(), "保存しました", Toast.LENGTH_SHORT).show(); } }); } }
実行結果は以下。EditTextで適当な値を登録し、保存ボタンを押すと入力した内容を「test」というキーで保管する。また、アプリケーション起動時には「test」キーからデータを読み出し、EditTextに表示する。
また、保存されたデータはEclipseのDDMSパースペクティブの「File Explorer」の、/data/data/sample.at/shared_prefs/MainActivity.xmlに保管されている。上記の画面の実行後のファイルの中身は以下のようになっている。
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="test">あいうえお</string> </map>
キー「test」に対して「あいうえお」という値が保管されているのが確認できる。