[アンドロイド] データベースtrongのアンドロイド – P1 TAOデータベース

みなさん、こんにちは, 今日私はあなたのシリーズを導くために始めます データベースtrongのアンドロイド. 鮮やかな具体的には、私はあなたがアプリケーションを作るためにガイドします “注意” 完全なユーザーデータベース.

私は英語で記述します。このシリーズのスクリプト. しかし、それは彼の英国スタイルの書き込みがあります “ベトナム語翻訳” だから、簡単に従います.
ここに: Androidのスタジオ 1.2.2
AndroidのSDK 5.1.1
ミンSDK: 4.0 (アンドロイド 4.0 上記のアプリを使用します)

JavaやC#SQLで、我々は、データを格納するのに精通またはmysqlのであれば、我々は保存するには、Androidでのsqliteを使用します.

他のシリーズでは、定期的にクラスを使用する男がリード にSQLiteDatabase 操作します, 私はあなたが組み合わせを使用するように指示します SQLiteOpenHelper 最も包括的なアップグレードを実行できるようにすることは、我々は簡単にデータベースを更新することができ、プロセス·アプリケーションであります.

ステップ 1: 作成したオブジェクトクラスが格納されているデータベース

このステップでは、クラスは、多くの場合、データベースのテーブルで作成します. 例えば、必要なクラスtb_noteテーブルノート.

file name: Note.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package cachhoc.net.tut.demodatabase;
 
public class Note {
    private long id;
    private String title;
    private String content;
     
    public String getTitle() {
        return title;
    }
 
    public Note setTitle(String title) {
        this.title = title;
        return this;
    }
 
    public long getId() {
        return id;
    }
 
    public Note setId(long id) {
        this.id = id;
        return this;
    }
 
    public String getContent() {
        return content;
    }
 
    public Note setContent(String content) {
        this.content = content;
        return this;
    }
}

あなた上記のコードでは設定方法に注意を払います. 彼の復帰は完全です。注意 (それはいつものクラス) これは、私たちは一連の値を容易にし、プログラムの実行時間を短縮することができます.

ステップ 2: データベースを初期化

このステップでは、データベースを実装します. あなたは、クラスを作成します DatabaseHelper 継承 SQLiteOpenHelper 次のように:

file name: DatabaseHelper.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cachhoc.net.tut.demodatabase;
 
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class DatabaseHelper extends SQLiteOpenHelper {
 
    public static final String DATABASE_NAME = "note.db";
 
    /**
     * table note contain id, title, content
     */
    public static final String TABLE_NOTE = "tb_note";
    public static final String KEY_ID_NOTE = "id";
    public static final String KEY_TITLE_NOTE = "title";
    public static final String KEY_CONTENT_NOTE = "content";
 
    /**
     * string for create table note
     */
    public static final String CREATE_TABLE_NOTE =
            "CREATE TABLE " + TABLE_NOTE + "(" +
                    KEY_ID_NOTE + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" +
                    ", " + KEY_TITLE_NOTE + " TEXT NOT NULL" +
                    "," + KEY_CONTENT_NOTE + " TEXT NOT NULL" +
                    ")";
 
    /**
     * value for update database
     */
    public static final int DATA_VERSION = 1;
 
    /**
     * Sqlite database
     */
    private SQLiteDatabase db;
 
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATA_VERSION);
    }
 
    /**
     * create db when app start, and only call when database don't create
     * When database created, it will not call
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_TABLE_NOTE);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * call when change DATA_VERSION
     * help we update database
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
    }
 
    /**
     * open database
     */
    public void open() {
        try {
            db = getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * close database
     */
    public void close() {
        if (db != null && db.isOpen()) {
            try {
                db.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

ここでは、次の点に注意を払うことができます:

  • 変数 DATABASE_NAME: 私達のデータベースの名前です. 各アプリケーションは、1つのデータベースを持っている必要があります.

  • テーブル tb_note 私たちの学校 イド, タイトルコンテンツ それぞれ、我々は文字列を持っています CREATE_TABLE_NOTE テーブルを作成するには

  • 変数 DATA_VERSION バージョンデータベースであります. あなたは次のバージョンでデータベースを変更したいとき、私たちは持っているデータベースのバージョンの更新まで上昇させます.

  • 変数 DB オブジェクトクラス にSQLiteDatabase データベース処理命令を操作するために可変になります

  • 方法 のonCreate クラスから上書き SQLiteOpenHelper 私たちはdatabseを作成するのに役立ちます.

  • 方法 ONUPGRADE 私たちはときにデータベースを更新するのに役立ちます DATA_VERSION 変化に.

  • メソッド オープン, クローズ クローズとオープンデータベースへ.

ステップ 3: 書き込み方法の基本的なデータベースクエリ

このステップでは、データを取得するには、いくつかの基本的なメソッドを記述します, データを挿入, 更新または削除.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/************************* method work with database *******************/
 
/**
 * get all row of table with sql command then return cursor
 * cursor move to frist to redy for get data
 */
public Cursor getAll(String sql) {
    open();
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor != null) {
        cursor.moveToFirst();
    }
    close();
    return cursor;
}
 
/**
 * insert contentvaluse to table
 *
 * @param values value of data want insert
 * @return index row insert
 */
public long insert(String table, ContentValues values) {
    open();
    long index = db.insert(table, null, values);
    close();
    return index;
}
 
/**
 * update values to table
 *
 * @return index row update
 */
public boolean update(String table, ContentValues values, String where) {
    open();
    long index = db.update(table, values, where, null);
    close();
    return index > 0;
}
 
/**
 * delete id row of table
 */
public boolean delete(String table, String where) {
    open();
    long index = db.delete(table, where, null);
    close();
    return index > 0;
}
/************************* end of method work with database *******************/

あなたは、SQLおよびMySQLに比べていくつかの新機能が表示されることがあり

  • 本手法でGETALLのカーソルを返します, そのレコードを指すようにポインタのようなものです (行) それはない持っているので、我々はコマンドを使用して最初の行を指すように設定する必要がどこに元のテーブルやポインティング cursor.moveToFirst();

  • 挿入モードでは、コール db.insert(テーブル, ヌル, 価値観), ここでの値は、クラスのオブジェクトであります ContentValues テーブルに挿入するコンテンツ. 我々はステップでそれを使用する方法を学習します 3.

  • インサート, 彼らはレコードが場所を挿入されている限り、整数型を返し、更新および削除, 更新または削除. 何の公的記録がなされていない場合 (エラー) それが返されます 0.

ステップ 4: テーブルに対するクエリメソッドを書きます

それが行われていたら 2 我々が作成し、データベースへのアクセスが完了した、あなたがしたい場合は、このステップをスキップすることができますように, 我々は照会するメソッドを呼び出すと、しかし、我々は別のクラスでいくつかの問題や長い処理が発生します. だから、簡単な方法を作るために、我々はそれぞれの特定のテーブルのクエリメソッドを作成する必要があります. ここでは、テーブルを取得する方法があるtb_note.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/************************* method work with note table *******************/
/**
 * get Note by sql command
 *
 * @param sql sql to get note
 */
public Note getNote(String sql) {
    Note note = null;
    Cursor cursor = getAll(sql);
    if (cursor != null) {
        note = cursorToNote(cursor);
        cursor.close();
    }
    return note;
}
 
/**
 * @param sql get all notes with sql command
 * @return arraylist of note
 */
public ArrayList<Note> getListNote(String sql) {
    ArrayList<Note> list = new ArrayList<>();
    Cursor cursor = getAll(sql);
 
    while (!cursor.isAfterLast()) {
        list.add(cursorToNote(cursor));
        cursor.moveToNext();
    }
    cursor.close();
 
    return list;
}
 
/**
 * insert note to table
 *
 * @param note note to insert
 * @return id of note
 */
public long insertNote(Note note) {
    return insert(TABLE_NOTE, noteToValues(note));
}
 
/**
 * @param note note to update
 * @return id of note update
 */
public boolean updateNote(Note note) {
    return update(TABLE_NOTE, noteToValues(note), KEY_ID_NOTE + " = " + note.getId());
}
 
/**
 * delete id row of table
 */
public boolean deleteNote(String where) {
    return delete(TABLE_NOTE, where);
}
 
/**
 * convert note to contentvalues
 * don't put id of note because
 * when insert id will auto create
 * when update we don't update id
 */
private ContentValues noteToValues(Note note) {
    ContentValues values = new ContentValues();
    values.put(KEY_TITLE_NOTE, note.getTitle());
    values.put(KEY_CONTENT_NOTE, note.getContent());
    return values;
}
 
/**
 * convert cursor to note
 */
private Note cursorToNote(Cursor cursor) {
    Note note = new Note();
    note.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID_NOTE)))
            .setTitle(cursor.getString(cursor.getColumnIndex(KEY_TITLE_NOTE)))
            .setContent(cursor.getString(cursor.getColumnIndex(KEY_CONTENT_NOTE)));
    return note;
}
/************************* end of method work note table *******************/

上記のコードでは、非常に明確にコメントしました, あなたが理解しよう.

完全なコード

ある程度 2 私はインターフェイススタイル材質イベントデザインを作るためにあなたを導き、完全なアプリの作成を開始します.

チュートリアルで行われた投稿 データベースtrongのアンドロイド によって nguyenvanquan7826


チュートリアルアンドロイド

[ポストをRPS-含ま=”4210″ ショートコード=”偽”]