「MIDPアプリ作成講座第7回::端末にデータを保存する方法」

By uchida - 09/04/08 - このエントリをはてなブックマークに追加このエントリをYahoo!ブックマークに追加このエントリをdel.icio.usに追加このエントリをFC2ブックマークに追加

au、ソフトバンクのアプリ作成講座、今回は端末にデータを保存する方法です。

前回のプログラムを少し変更して、メモした内容を保存するサンプルを作ってみました

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Spacer;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;

public class Midp07 extends MIDlet {
	
	public Midp07(){
		//フォーム生成
		Midp07Form mainForm = new Midp07Form();
		
		//カレントフレームにフォームを設定
		Display.getDisplay(this).setCurrent(mainForm);
	}
	
	protected void startApp() {
	}
	
	protected void pauseApp() {
	}
	
	protected void destroyApp(boolean unconditional) {
	}
}

class Midp07Form extends Form implements ItemCommandListener{

	StringItem  clearButton;
	StringItem  readButton;
	StringItem  writeButton;
	TextField   inputTextBox;
	RecordStore record = null;
	
	/** コンストラクタ **/
	Midp07Form(){
		super("メモ帳");
		
		//入力テキスト
		append(new Spacer(240,5));
		inputTextBox = new TextField("入力内容", "", 200, TextField.ANY);
		inputTextBox.setInitialInputMode("UCB_HIRAGANA");
		append(inputTextBox);
		
		//クリアボタン
		append(new Spacer(240,5));
		clearButton = new StringItem("クリア","",Item.BUTTON);
		clearButton.setLayout(Item.LAYOUT_CENTER);
		clearButton.setDefaultCommand(new Command("",Command.SCREEN,0));
		clearButton.setItemCommandListener(this);
		append(clearButton);
		
		//読込ボタン
		append(new Spacer(240,5));
		readButton = new StringItem("読込","",Item.BUTTON);
		readButton.setLayout(Item.LAYOUT_CENTER);
		readButton.setDefaultCommand(new Command("",Command.SCREEN,0));
		readButton.setItemCommandListener(this);
		append(readButton);
		
		//保存ボタン
		append(new Spacer(240,5));
		writeButton = new StringItem("保存","",Item.BUTTON);
		writeButton.setLayout(Item.LAYOUT_CENTER);
		writeButton.setDefaultCommand(new Command("",Command.SCREEN,0));
		writeButton.setItemCommandListener(this);
		append(writeButton);
	}
	
	public void commandAction(Command cmd,Item item){
        if (item==clearButton) {
        	//テキストクリア
    		System.out.println("テキストクリアしました。");
    		inputTextBox.setString("");
        }else if(item==readButton){
        	//データ読込
        	String memo = "";
        	try{
	            //レコードストアの接続
	           record = RecordStore.openRecordStore("memo",false);
                   
                  //レコードストアを読込
	           byte[] b = record.getRecord(1);
	           memo = new String(b);
	           inputTextBox.setString(memo);
	          
                   //レコードストアの切断
	           record.closeRecordStore();
	        	
        	}catch(RecordStoreException e){
        		e.printStackTrace();
        	}
        }else if(item==writeButton){
        	//データ書込
        	try{
	            //レコードストアの接続
	        	record = RecordStore.openRecordStore("memo",true);
	        	
	                //レコードの追加
	        	String data = inputTextBox.getString();
	        	byte[] b = data.getBytes();

	                if (record.getNumRecords()==0) {
	                    record.addRecord(b,0,b.length);
	                }else{
			    record.setRecord(1,b,0,b.length);

	                }
	        	
                        //レコードの切断
	        	record.closeRecordStore();
	        	
	        	
        	}catch(RecordStoreException e){
        		e.printStackTrace();
        	}
        }
	}
	
}

概要

前回からボタンを2つ追加しています。
1.書込
2.読込
 
機能としてはテキストフィールドにテキストを入力して、書込ボタンでデータを保存します。
そして読込ボタンで保存しておいたデータを読込ボタンを押してテキストフィールドに反映させます。
 

プログラムの解説

MIDPではレコードストアという端末の領域にデータを保存します。
利用にあたり、以下のクラスをインポートします。
import javax.microedition.rms.*;
 
利用する手順は、接続→保存→切断となります。
 
保存する領域はレコードIDで管理されており、名前を好みで設定できます。
この辺りはDojaのスクラッチパッドとは大きく違うところです。
 
では、実際のソースを追って利用する手順を具体的に説明します。

//レコードストアの接続
record = RecordStore.openRecordStore("memo",true);

まず、接続の部分から。
RecordStore.openRecordStoreで接続を行います。
ここで指定した”memo”がレコードIDになります。

//レコードの追加
String data = inputTextBox.getString();
byte[] b = data.getBytes();

if (record.getNumRecords()==0) {
     record.addRecord(b,0,b.length);
}else{
    record.setRecord(1,b,0,b.length);

}

次にレコードを保存します。
String dataにテキストフィールドの値を保存し、byte型配列に変換しbに代入しています。
getNumRecordsでレコードの存在の有無を確認し、無ければデータを登録し有れば変更するようになっています。

//レコードの切断
record.closeRecordStore();

最後に使用したレコードを切断して終了です。
 
※ファイル操作の場合はかならず例外処理をいれておきましょう。
 

//レコードストアの接続
record = RecordStore.openRecordStore("memo",false);

ここからはデータの読込をする箇所です。
書込の時と同じようにRecordStore.openRecordStoreで接続します。
第2引数はfalseになります。
 

//レコードストアを読込
byte[] b = record.getRecord(1);
memo = new String(b);
inputTextBox.setString(memo);

record.getRecordで読込、バイト型配列にデータを格納し、その結果を文字列型に変換してテキストフィールドに反映しています。
 

//レコードストアの切断
record.closeRecordStore();

切断は保存の時と同じですね。