Tips

SQLiteデータベースの基礎を理解できるAndroidサンプルアプリ

SQLiteデータベースの各操作を知る

自作のアプリからカレンダーの編集画面に移動する

※はじめに
この記事はAndroidアプリの開発が、初心者であるという方のための記事です。
そのため、なるべく複雑な説明は避け、コピー&ペイストですぐに動くものをご紹介します。
JavaやAndroidを理解されている方で細かい説明が必要な方は、当ブログ内の連載記事である「Android Tips」をご覧ください。

今回はSQLiteを用いたアプリです。
下図のように各ボタンを押下すると、登録、更新、削除、すべて削除といった各処理を実行します。

アプリの操作

  • 登録
    1. 「名前」と「年齢」を入力
    2. 「登録ボタン」を押下
    3. 「データベースの中身を閲覧」ボタンを押下すると、入力した名前と年齢が登録されていることがわかる。
  • 更新
    1. 「データベースに存在している名前」と「年齢」を入力
    2. 「更新ボタン」を押下
    3. 「データベースの中身を閲覧」ボタンを押下すると、該当の名前の年齢が更新されていることがわかる。
  • 選択削除
    1. 「データベースに存在している名前」を入力
    2. 「削除ボタン」を押下
    3. 「データベースの中身を閲覧」ボタンを押下すると、該当の名前と年齢が削除されていることがわかる。
  • すべて削除
    1. 「すべて削除ボタン」を押下
    2. 「データベースの中身を閲覧」ボタンを押下すると、テーブル内のすべてのデータが削除されていることがわかる。

アプリ情報

アプリ完成図

  • 登録ボタンを押下
  • 1

    2

    3

  • 更新ボタンをクリック
  • 4

    5

    6

  • 削除ボタンをクリック
  • 7

    8

    9

  • すべて削除をクリック
  • 10

    11

    12

MainActivity.java(ソースコード)

activity_main.xmlと紐づきたActivityです。
各ボタンを押下したときの処理を記述しています。

1
2
3
4
5
6
7
8
9
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.example.sqlitesample1;
 
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
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 {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        MyOpenHelper helper = new MyOpenHelper(this);
        final SQLiteDatabase db = helper.getWritableDatabase();
 
        final EditText nameText = (EditText) findViewById(R.id.editName);
        final EditText ageText = (EditText) findViewById(R.id.editAge);
 
        Button entryButton = (Button) findViewById(R.id.insert);
        entryButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                String name = nameText.getText().toString();
                String age = ageText.getText().toString();
 
                ContentValues insertValues = new ContentValues();
                insertValues.put("name", name);
                insertValues.put("age", age);
                long id = db.insert("person", name, insertValues);
            }
        });
 
        Button updateButton = (Button) findViewById(R.id.update);
        updateButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                String name = nameText.getText().toString();
                String age = ageText.getText().toString();
 
                if (name.equals("")) {
                    Toast.makeText(MainActivity.this, "名前を入力してください。",
                            Toast.LENGTH_SHORT).show();
                } else {
                    ContentValues updateValues = new ContentValues();
                    updateValues.put("age", age);
                    db.update("person", updateValues, "name=?", new String[] { name });
                }
            }
        });
 
        Button deleteButton = (Button) findViewById(R.id.delete);
        deleteButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                String name = nameText.getText().toString();
                String age = ageText.getText().toString();
 
                if (name.equals("")) {
                    Toast.makeText(MainActivity.this, "名前を入力してください。",
                            Toast.LENGTH_SHORT).show();
                } else {
                    db.delete("person", "name=?", new String[] { name });
                }
 
            }
        });
 
        Button deleteAllButton = (Button) findViewById(R.id.deleteAll);
        deleteAllButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                String name = nameText.getText().toString();
                String age = ageText.getText().toString();
 
                db.delete("person", null, null);
 
            }
        });
 
        Button detaBaseButton = (Button) findViewById(R.id.dataBase);
        detaBaseButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                Intent dbIntent = new Intent(MainActivity.this,
                        ShowDataBase.class);
                startActivity(dbIntent);
 
            }
        });
    }
}

MyOpenHelper.java

SQLiteOpenHelperを継承したクラスで、SQLiteデータベースを生成しているActivityです。
レイアウトファイルとは紐づけていないので、目には見えません。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example.sqlitesample1;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class MyOpenHelper extends SQLiteOpenHelper {
 
    public MyOpenHelper(Context context) {
        super(context, "NameAgeDB", null, 1);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person(" + " name text not null," + "age text"
                + ");");
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
    }
 
}

ShowDataBase.java

show_database.xmlと紐づいたActivityです。
データベースの中身を表示させるための処理を記述しています。

1
2
3
4
5
6
7
8
9
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
package com.example.sqlitesample1;
 
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
 
public class ShowDataBase extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_database);
 
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
 
        MyOpenHelper helper = new MyOpenHelper(this);
        SQLiteDatabase db = helper.getReadableDatabase();
 
        // queryメソッドの実行例
        Cursor c = db.query("person", new String[] { "name", "age" }, null,
                null, null, null, null);
 
        boolean mov = c.moveToFirst();
        while (mov) {
            TextView textView = new TextView(this);
            textView.setText(String.format("%s : %d歳", c.getString(0),
                    c.getInt(1)));
            mov = c.moveToNext();
            layout.addView(textView);
        }
        c.close();
        db.close();
    }
}

activity_main.xml

アプリ起動時に表示されるメイン画面です。

1
2
3
4
5
6
7
8
9
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
 
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="名前と年齢を入力してください。"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:text="名前" />
 
    <EditText
        android:id="@+id/editName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView2"
        android:ems="10"
        android:inputType="textPersonName" >
 
        <requestFocus />
    </EditText>
 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/editName"
        android:text="年齢" />
 
    <EditText
        android:id="@+id/editAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView3"
        android:ems="10"
        android:inputType="number" />
 
    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editAge"
        android:text="登録" />
 
    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editAge"
        android:layout_toRightOf="@+id/insert"
        android:text="更新" />
 
    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/update"
        android:layout_alignBottom="@+id/update"
        android:layout_toRightOf="@+id/update"
        android:text="削除" />
 
    <Button
        android:id="@+id/deleteAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/delete"
        android:layout_alignBottom="@+id/delete"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@+id/delete"
        android:text="すべて削除" />
 
    <Button
        android:id="@+id/dataBase"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:text="データベースの中身を閲覧" />
 
</RelativeLayout>

show_database.xml

データベースの内容を閲覧するための画面です。
このファイル自体には何もしていませんが、ShowDataBase.javaの中に記述しているレイアウトはこの画面にセットされます。

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
</LinearLayout>

AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.sqlitesample1"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sqlitesample1.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MyOpenHelper" >
        </activity>
        <activity android:name=".ShowDataBase"></activity>
    </application>
 
</manifest>

これでOKです。

お勧め書籍

[amazonjs asin=”4844335197″ locale=”JP” title=”初歩からわかるAndroid最新プログラミング 増補改訂版”] [amazonjs asin=”4844331272″ locale=”JP” title=”本格アプリを作ろう! Androidプログラミングレシピ”] [amazonjs asin=”4863541309″ locale=”JP” title=”中学生でもわかる Androidアプリ開発講座”]

Androidアプリ開発の必須知識!JAVAプログラミングを学べる連載リンク

はじめてのJAVA 連載

Recent News

Recent Tips

Tag Search