package net.npaka.sqliteex;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//データベースの読み書き
public class SQLiteEx extends Activity implements
View.OnClickListener,
DialogInterface.OnClickListener {
private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT;
private final static String DB_NAME ="test.db";//DB名
private final static String DB_TABLE="test"; //テーブル名
private final static int DB_VERSION=1; //バージョン
private SQLiteDatabase db;
private TableLayout table;
private String[][] records;
private EditText dlgEdit;
private String id;
//テキストダイアログの表示
private void showTextDialog(final Context context,
String title,String message,
DialogInterface.OnClickListener listener,String tag) {
dlgEdit=new EditText(context);
dlgEdit.setTag(tag);
AlertDialog.Builder ad=new AlertDialog.Builder(context);
ad.setTitle(title);
ad.setMessage(message);
ad.setView(dlgEdit);
ad.setPositiveButton("OK",listener);
ad.setNegativeButton("キャンセル",null);
ad.show();
//ソフトウェアキーボードを開く
dlgEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v,boolean hasFocus) {
if (!hasFocus) return;
Handler handler=new Handler();
Message m=Message.obtain(handler,new Runnable() {
public void run() {
InputMethodManager imm=(InputMethodManager)
getSystemService(INPUT_METHOD_SERVICE);
imm.showSoftInput(dlgEdit,
InputMethodManager.SHOW_IMPLICIT);
}
});
handler.sendMessage(m);
}
});
dlgEdit.requestFocus();
}
//テーブルの更新
private void updateTable() {
readRecords();
table.removeAllViews();
for (int j=0;j<records.length;j++) {
//行の生成
TableRow row=new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(WC,WC));
row.setGravity(Gravity.CENTER);
table.addView(row);
//要素の追加
for (int i=0;i<records[j].length;i++) {
TextView textView=new TextView(this);
textView.setTextColor(Color.BLACK);
textView.setText(records[j][i]);
ShapeDrawable shape=new ShapeDrawable(new RectShape());
shape.getPaint().setStyle(Paint.Style.STROKE);
textView.setBackgroundDrawable(shape);
row.addView(textView);
}
}
}
//ボタンの生成
private Button makeButton(String text,String tag) {
Button button=new Button(this);
button.setText(text);
button.setTag(tag);
button.setOnClickListener(this);
button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
return button;
}
//初期化
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//レイアウトの生成
LinearLayout layout=new LinearLayout(this);
layout.setBackgroundColor(Color.rgb(255,255,255));
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
//テーブルの生成
table=new TableLayout(this);
table.setBackgroundColor(Color.WHITE);
table.setGravity(Gravity.CENTER);
table.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
layout.addView(table);
//ボタンの生成
layout.addView(makeButton("レコードの追加","addRecord0"));
layout.addView(makeButton("レコードの削除","delRecord"));
//データベースオブジェクトの生成
DBHelper dbHelper=new DBHelper(this);
db=dbHelper.getWritableDatabase();
updateTable();
}
//ボタンクリックイベントの処理
public void onClick(View v) {
String tag=(String)v.getTag();
showTextDialog(this,"","レコードのIDを入力",this,tag);
}
//ダイアログボタンクリック時に呼ばれる
public void onClick(DialogInterface dialog,int which) {
String text=dlgEdit.getText().toString();
String tag =(String)dlgEdit.getTag();
if (tag.endsWith("addRecord0")) {
id=text;
showTextDialog(this,"","レコードの値を入力",this,"addRecord1");
} else if (tag.endsWith("addRecord1")) {
addRecord(id,text);
updateTable();
} else if (tag.endsWith("delRecord")) {
delRecord(text);
updateTable();
}
}
//レコード群の読み込み
private void readRecords() {
Cursor c=db.query(DB_TABLE,new String[]{"id","info"},
null,null,null,null,"id");
records=new String[c.getCount()][2];
if (c.moveToFirst()) {
int j=0;
do {
records[j][0]=c.getString(0);
records[j][1]=c.getString(1);
j++;
} while(c.moveToNext());
}
c.close();
}
//レコードの追加
private void addRecord(String id,String info) {
ContentValues values=new ContentValues();
values.put("id",id);
values.put("info",info);
int colNum=db.update(DB_TABLE,values,"id='"+id+"'",null);
if (colNum==0) db.insert(DB_TABLE,"",values);
}
//レコードの削除
private void delRecord(String id) {
db.delete(DB_TABLE,"id='"+id+"'",null);
}
//データベースヘルパーの定義
private static class DBHelper extends SQLiteOpenHelper {
//コンストラクタ
public DBHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION);
}
//データベースの生成
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists "+
DB_TABLE+"(id text primary key,info text)");
}
//データベースのアップグレード
@Override
public void onUpgrade(SQLiteDatabase db,
int oldVersion,int newVersion) {
db.execSQL("drop talbe if exists "+DB_TABLE);
onCreate(db);
}
}
} |