2013年03月24日

Androidアプリでデータ保存、その1【KeyValue編】

前回はアクティビティの状態を保存するためのInstanceStateを紹介した。

今回はAndroidアプリでデータを保存する方法を紹介する。(※以下で紹介するソースは前回作ったプロジェクトを土台にしているのでご注意)

まずAndroidアプリではデータを永続化するためには以下の3つの方法が用意されている。

1) KeyValueセット
2) ファイル
3) データベース

これを踏まえて、
今回は一つ目の「KeyValueセット」を使ってデータを保存する方法を紹介したいと思う。

これは説明するまでもなく、「キーを指定して値を取得する」という、非常にシンプルかつ便利な仕組みである。

KeyValueセットでデータを保存するには、SharedPreferencesというクラスを使う。

早速サンプルを見てみよう。

まずはメッセージリソースから。
/res/values/string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="title_activity_display_message">My Message</string>

<!-- SharedPreferences -->
<string name="sp_key">my_sp_key</string>
<string name="button_save_to_sp">save to SP</string>
<string name="button_read_from_sp">read from SP</string>

</resources>


次に画面定義。
/res/layout/activity_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" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<EditText
android:id="@+id/edit_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/edit_message" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="@string/button_send" />
</LinearLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="saveToSP"
android:text="@string/button_save_to_sp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="readFromSP"
android:text="@string/button_read_from_sp" />
</LinearLayout>

</LinearLayout>


最後はJavaソースだ。
/src/com/example/myfirstapp/MainActivity.java

package com.example.myfirstapp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

// InstanceStateへ状態を保存するためのキー
public final static String STATE_ENTERED_MESSAGE = "state.enteredmessage";

private String message = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}

/**
* メッセージをSharedPreferencesへ保存
*/
public void saveToSP(View view) {
// 入力ボックスの値を取得
EditText editText = (EditText) findViewById(R.id.edit_message);
message = editText.getText().toString();
// SPへ保存
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.sp_key), message);
editor.commit();
// トースト表示
Toast.makeText(this, "SPへ保存しました:" + message, Toast.LENGTH_LONG).show();
}

/**
* SharedPreferencesに保存されたメッセージを読み込み
*/
@SuppressLint("ShowToast")
public void readFromSP(View view) {
// SPからデータを取得
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String message = sharedPref.getString(getString(R.string.sp_key),
"default message");
// トースト表示
Toast.makeText(this, "SPから読み込みました:"+message, Toast.LENGTH_LONG).show();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
// InstanceState へ 入力されたメッセージを保存しておく。
outState.putString(STATE_ENTERED_MESSAGE, message);
super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
message = savedInstanceState.getString(STATE_ENTERED_MESSAGE);
}

}


このアプリは、「save to SP」ボタンを押すことで、テキストボックスに入力された文字列をKeyValueセットとして保存され、「read from SP」ボタンを押すことでそれを読み込んでトースト表示する。

ポイントは、saveToSPメソッドとreadToSPメソッドの中身だ。
getPreferencesメソッドでSharedPreferencesを取得して、そこからgetStringしたり、getIntしたり、、、ごにょごにょすればよいだけ。
データを保存するときは SharedPreferencesからEditorを取り出して、putStringなり、putIntなりして、最後にcommitする。

SharedPreferencesはちょっとしたデータをサクッと保存する場合にとても使い勝手がよさそうである。

次回はFileへの保存方法を紹介する予定。
posted by 寄り道退屈男 at 11:53 | Comment(0) | TrackBack(0) | Android
この記事へのコメント
コメントを書く
お名前: [必須入力]

メールアドレス: [必須入力]

ホームページアドレス:

コメント: [必須入力]

認証コード: [必須入力]


※画像の中の文字を半角で入力してください。
この記事へのトラックバックURL
http://blog.sakura.ne.jp/tb/64015105
※言及リンクのないトラックバックは受信されません。

この記事へのトラックバック