PG備忘録

プログラミングいろいろ

SQLiteのデータの追加・更新・削除・全削除・表示

f:id:olee46:20170531165628j:plain

機能
・レコードの追加
・レコードの更新
・レコードの削除
・レコードの全削除
・レコードの表示

activity_main.xml
f:id:olee46:20170531165626j:plain


MainActivity.java

package com.example.orisa.mydb5;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText addName;
    EditText addAge;
    Button addBtn;
    Button updateBtn;
    Button deleteBtn;
    Button deleteAllBtn;
    Button showBtn;

    TextView disp;

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

        //部品の取得
        addName = (EditText)findViewById(R.id.addName);
        addAge = (EditText)findViewById(R.id.addAge);
        addBtn = (Button)findViewById(R.id.addBtn);
        updateBtn = (Button)findViewById(R.id.updateBtn);
        deleteBtn = (Button)findViewById(R.id.deleteBtn);
        deleteAllBtn = (Button)findViewById(R.id.deleteAllBtn);
        showBtn = (Button)findViewById(R.id.showBtn);
        disp = (TextView)findViewById(R.id.disp);

        //データベースの生成
        MyDbHelper hlp = new MyDbHelper(this);
        final SQLiteDatabase db = hlp.getReadableDatabase(); //finalをつけるのに注意

        //データを追加
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues val = new ContentValues();
                val.put("name", addName.getText().toString());
                val.put("age", addAge.getText().toString());
                db.insert("person", null, val);
            }
        });

        //データの更新
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //nameとageを取得
                String name = addName.getText().toString();
                String age = addAge.getText().toString();

                //ContentValuesに値を入れる
                ContentValues val = new ContentValues();
                val.put("age", age);

                //データベースを更新
                db.update("person", val, "name=?", new String[]{name});
            }
        });

        //データの削除
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //名前を取得
                String name = addName.getText().toString();

                //ContentValuesに値を入れる
                ContentValues val = new ContentValues();
                val.put("name", name);

                //データベースを更新
                db.delete("person", "name=?", new String[]{name});
            }
        });

        //データの全削除
        deleteAllBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db.delete("person", null, null);
            }
        });

        //データを表示
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TextViewをリセットする
                disp.setText(null);
                Cursor c = db.query("person", new String[]{"name", "age"}, null, null, null, null, null);
                boolean mov = c.moveToFirst();
                while(mov){
                    disp.append(c.getString(0) + ": " + c.getInt(1) + "\n");
                    mov = c.moveToNext();
                }
                c.close();
            }
        });
    }
}

MyDbHelper.java

package com.example.orisa.mydb5;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by orisa on 2017/05/31.
 */

public class MyDbHelper extends SQLiteOpenHelper {
    public MyDbHelper(Context context){
        super(context, null, null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE person(name TEXT NOT NULL, age TEXT);");

        //insert data
        db.execSQL("INSERT INTO person(name, age) values('john', 18);");
        db.execSQL("INSERT INTO person(name, age) values('eric', 20);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


参考サイト
SQLiteデータベースの基礎を理解できるAndroidサンプルアプリ | TECH Projin

SQLiteのデータの追加・表示

f:id:olee46:20170531141239j:plain
機能:
・レコードの追加
・全レコードの表示

必要なクラス
・MainActivity.java
・MyDbHelper.java (SQLLiteOpenHelperを実装)

MainActivity.java

package com.example.orisa.mydb3;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    //部品の変数
    RelativeLayout layout;
    TextView tv;//データベースを表示するテキストビュー
    EditText addName;//名前の入力
    EditText addAge;//年齢の入力
    Button addBtn;//データの追加
    Button showBtn;//データベースの表示


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

        //部品の取得
        layout = (RelativeLayout) findViewById(R.id.layout);
        tv = (TextView)findViewById(R.id.tv) ;
        addName = (EditText)findViewById(R.id.addName);
        addAge = (EditText)findViewById(R.id.addAge);
        addBtn = (Button)findViewById(R.id.addBtn);
        showBtn = (Button)findViewById(R.id.showBtn);

        //データベースの生成
        MyDbHelper hlp = new MyDbHelper(this);
        final SQLiteDatabase db = hlp.getReadableDatabase();

        //データの取得と追加
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ContentValuesにデータを入れる
                ContentValues val = new ContentValues();
                val.put("name", addName.getText().toString());
                val.put("age", addAge.getText().toString());

                //データベースにレコードを挿入
                db.insert("person_table", null, val);
            }
        });

        //データの読み出し
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //テキストビューをリセットする
                tv.setText(null);

                //全レコードを表示
                Cursor c = db.query("person_table", new String[]{"name, age"},
                        null, null, null, null, null);
                boolean mov = c.moveToFirst();
                while (mov){
                    //一つのレコードを追加
                    tv.append(String.format("%s: %d才", c.getString(0), c.getInt(1)));
                    //改行
                    tv.append("\n");
                    mov = c.moveToNext();
                }
                c.close();
            }
        });

    }
}


MyDbHelper.java

package com.example.orisa.mydb3;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by orisa on 2017/05/30.
 */

public class MyDbHelper extends SQLiteOpenHelper {
    public MyDbHelper(Context context){
        super(context, null, null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE person_table(name TEXT NOT NULL, age TEXT);");

        //データを挿入する
        db.execSQL("INSERT INTO person_table(name, age) values(?,?);", new Object[]{"Adam Smith", 30});
        db.execSQL("INSERT INTO person_table(name, age) values(?,?);", new Object[]{"John Lennon", 40});
        db.execSQL("INSERT INTO person_table(name, age) values(?, ?);", new Object[]{"Paul McCartney", 50});


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


activity_main.xml
f:id:olee46:20170531141248j:plain



参考サイト
SQLiteでデータベース - 愚鈍人

EditTextからStringを取得する

EditTextからStringを取得するときのコードは

editText.getText().toString;

メソッドについて、

メソッド 戻り値
getText() Editable

だが、EditableクラスにtoStringはない
https://developer.android.com/reference/android/text/Editable.html

が、Editableクラスを実装したSpannableStringBuilderクラスには

メソッド 戻り値
toString() String

があるので、これを使って文字列を取得する



参考サイト
www.javadrive.jp

SQLiteの注意点

        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor c = db.query("person_table", new String[]{"name, age"},
                        null, null, null, null, null);
                boolean mov = c.moveToFirst();
                while (mov){
                    tv.append(String.format("%s: %d才", c.getString(0), c.getInt(1)));
                    tv.append("\n");
                    mov = c.moveToNext();
                }
                c.close();
                db.close();
            }
        });
c.close();
db.close();

を入れないとエラーを吐くので注意

データベースの生成・追加・表示のサンプルコード

MainActivity.java

package com.example.orisa.mydb3;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    //部品の変数
    LinearLayout layout;
    TextView tv;

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

        //部品の取得
        layout = (LinearLayout)findViewById(R.id.layout);
        tv = (TextView)findViewById(R.id.tv) ;

        //データベースの生成
        MyDbHelper hlp = new MyDbHelper(this);
        SQLiteDatabase db = hlp.getReadableDatabase();

        //データの追加
        ContentValues val = new ContentValues();
        val.put("name", "Ming Ho");
        val.put("age", 44);
        db.insert("person_table", null, val);

        //データの読み出し
        Cursor c = db.query("person_table", new String[]{"name, age"},
                null, null, null, null, null);
        boolean mov = c.moveToFirst();
        while (mov){
            tv.append(String.format("%s: %d才", c.getString(0), c.getInt(1)));
            tv.append("\n");
            mov = c.moveToNext();
        }
        c.close();
        db.close();
    }
}

MyDbHelper

package com.example.orisa.mydb3;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by orisa on 2017/05/30.
 */

public class MyDbHelper extends SQLiteOpenHelper {
    public MyDbHelper(Context context){
        super(context, null, null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE person_table(name TEXT NOT NULL, age TEXT);");

        //データを挿入する
        db.execSQL("INSERT INTO person_table(name, age) values(?,?);", new Object[]{"Adam Smith", 30});
        db.execSQL("INSERT INTO person_table(name, age) values(?,?);", new Object[]{"John Lennon", 40});
        db.execSQL("INSERT INTO person_table(name, age) values(?, ?);", new Object[]{"Paul McCartney", 50});


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

SQLiteの使い方① データベースの削除

//データベースの生成
MyDBHelper helper = new MyDBHelper(this);
SQLLiteDatabase db = helper.getWritableDatabase();

//データベースのデータを削除
//フィールド名が「yamada」のレコードを削除
db.delete("mytable", "name= ?”, new String[]{“yamada″});

//データベースのデータを全削除
db.delete("mytable", null, null);
int delete(String table, String whereClause, String[] whereArgs)

・table: テーブルの名前
・whereClase: フィールド名
・whereArgs: 検索値

上の例だと、↓のSQL文に対応する

DELETE FROM mytable WHERE name='yamada';

SQLiteの使い方① データベースの作成

①SQLiteOpenHelperを実装したMyDBHelperクラスをつくる→データベースの設定をする

public class MyDBHelper extends SQLiteOpenHelper {

    //コンストラクタ
    public MyDBHelper (Context context){
        //DBを作成
        super(context, "testdb", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE testtb(_id INTEGER PRIMARY KEY, comment TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}


②MainActivityでデータベースを作る

MyDBHelper helper = new MyDBHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();

メソッドの説明

SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

・context: コンテキスト
MainActivityの中でthisを受け取る
・name: データベースの名前
・factory: nullでok
・version: データベースのバージョン; 大体1でok

void onCreate(SQLiteDatabase db)

データベースが初めて作られるときに呼ばれるメソッド

void execSQL(String sql)

・string: SQL文をいれる
SELECT以外のCREATE, INSERT, DELETEなどデータを受け取らないSQL文を受け取れる

void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

データベースがバージョンアップしたときに呼び出される
大体中身は空でok

SQLiteDatabase getWritableDatabase()

読み書き可能なデータベースをつくる


参考サイト:
https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.htmldeveloper.android.com
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmldeveloper.android.com
it-trick-java.appspot.com
www.appli-info.jp