[[FrontPage]]

#contents

2011/07/31からのアクセス回数 &counter;

** テーブルビューをデータベースに保存 [#g38726dd]
[[titanium/テーブルビューを作る]]
の結果をデータベースに保存できるようにします。

ここでも
[[Titanium Mobileで作る! iPhone/Androidアプリ第10回>http://gihyo.jp/dev/serial/01/titanium/0010]]
を参考にものまねします。

データベースにテーブルrecordsを作成し、カラムに
- id: 整数の識別子主キー
- weight: 体重(text)
- at: 計測日(real)

SQLiteでは、日付はtextまたはrealで保持するのが一般できみたいですが、textではソートが正しく行われないため、ここではrealを使います。

プログラムの以下のようになります。

redord_db.js
#pre{{
var RecordDB = function() {
    this.dbName = 'recorddb';
    
    this.open = function () {
        this.db = Titanium.Database.open(this.dbName);
    };

    this.close = function () {
        this.db.close();
    };

	this.setRows = function (rows) {
		var res = [];
        if ( rows.getRowCount() > 0 ) {
            Ti.API.debug('Found: ' + rows.getRowCount() );
            for (i =0; rows.isValidRow(); i++) {
                var record = {};
                record.id = rows.fieldByName('id');
                record.weight = rows.fieldByName('weight');
                var time = rows.fieldByName('at', Titanium.Database.FIELD_TYPE_DOUBLE)
                record.at = new Date();
                record.at.setTime(time);
                res.push(record);
                rows.next();
            }
        }
        return res;		
	};

	this.deleteOne = function(record) {
        this.open();
        var res = this.db.execute(
            'DELETE FROM records WHERE id=?',
            record.id
        );
        Ti.API.debug('Delete from DB');
        this.close();
        return true;							
	};
	
	this.update = function(record) {
        this.open();
        Ti.API.debug('update at.getTime():' + record.at.getTime());
        var res = this.db.execute(
            'UPDATE records SET weight=?, at=? WHERE id=?',
            record.weight,
            record.at.getTime(),
            record.id
        );
        Ti.API.debug('Update DB');
        this.close();
        return true;				
	};
	
	this.insert = function(record) {
        this.open();
        Ti.API.debug('insert at.getTime():' + record.at.getTime());
        var res = this.db.execute(
            'INSERT INTO records (weight, at) VALUES(?,?)',
            record.weight,
            record.at.getTime()
        );
        Ti.API.debug('Insert into DB');
        this.close();
        return id;		
	};
	
    this.findAll = function() {
        this.open();
        var rows = this.db.execute( 'SELECT * FROM records ORDER BY at DESC' );
        var res = this.setRows(rows);        
        rows.close();
        this.close();
        return res;
    };
		
	// テーブル作成
    this.open();
    //this.db.execute('DROP TABLE records');
    this.db.execute('CREATE TABLE IF NOT EXISTS records ( id INTEGER PRIMARY KEY, weight TEXT, at real)');
    this.close();
};
}}

record_db.jsにデータベースの基本処理を定義します。

** コメント [#l2c782be]
#vote(おもしろかった,そうでもない,わかりずらい)

皆様のご意見、ご希望をお待ちしております。
#comment_kcaptcha

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
SmartDoc