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
Buttonにリスナーをつける
//画面上の部品をコード上の変数に割り当てる Button dataBaseButton = (Button)findViewById(R.id.dataBase); //Buttonにリスナーをつける dataBaseButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //処理内容を記述 } });
概要
①変数に部品を割り当てる
②ボタンに setOnClickListener メソッドをつける
③setOnclickListener の引数の中で OnClickListener を記述
④OnClickListener の中身で処理内容を記述
Intent/画面遷移の方法
サンプルコード
Intent dbIntent = new Intent(MainActivity.this,ShowDataBase.class); startActivity(dbIntent);
概要
①Intentオブジェクトを作って、元の画面と遷移先の画面を指定
②Intentオブジェクトを開始
メソッドの説明
Intent(Context packageContext, Class<?> cls)
遷移の内容を指定
packageContext | 遷移元の画面 |
cls | 遷移先の画面 |
startActivity(Intent intent)
intentオブジェクトを引数に、遷移を開始する
Toastを表示させる方法
概要
①makeTextで表示させる内容を設定
②showで表示させる
メソッドの説明
makeText(Context context, CharSequence text, int duration)
・Context context: 表示させる場所
thisを入れておけば大体ok
・CharSequence text: 表示させる内容
Stringをそのまま入れてok
String以外でも、CharSequenceを実装しているクラス(e.g. StringBuffer)であればok
・int duration: 表示させる時間
LENGTH_LONGとLENGTH_SHORTの2つの定数が利用できる
使うときは前にToast.を入れることに注意