package com.example.Database;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class DatabaseActivity extends Activity implements
Button.OnClickListener {
DBAdapter db_ex;
long id;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 通过此类来进行数据库的相关操作
db_ex = new DBAdapter(this, Constants.DB_NAME, Constants.DB_VERSION);
Button add_btn = (Button) findViewById(R.id.Button01);
Button cancel_btn = (Button) findViewById(R.id.Button02);
Button update_btn = (Button) findViewById(R.id.Button03);
Button check_btn = (Button) findViewById(R.id.Button04);
add_btn.setOnClickListener(this);
cancel_btn.setOnClickListener(this);
update_btn.setOnClickListener(this);
check_btn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.Button01:
// ---add 2 titles---
// 每次操作数据库都要调用此函数open()
db_ex.open();
id = db_ex.insertTitle("1111111", "Android book", "Jim");
id = db_ex.insertTitle("2222222", "Iphone book", "Edison");
// ---获取所有标题---
Cursor c = db_ex.getAllTitles();
if (c.moveToFirst()) {
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db_ex.close();
break;
case R.id.Button02:
// 删除一行数据
db_ex.open();
if (db_ex.deleteTitle(1)) {
Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG)
.show();
}
db_ex.close();
break;
case R.id.Button03:
// 更新一条数据
db_ex.open();
if (db_ex.updateTitle(1, "1234567", "Programmer's Reference",
"Wrox Press")) {
Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG)
.show();
}
// 将更新后的数据显示出来
Cursor c1 = db_ex.getTitle(1);
if (c1.moveToFirst()) {
DisplayTitle(c1);
} else {
Toast.makeText(this, "No title found", Toast.LENGTH_LONG)
.show();
}
db_ex.close();
break;
case R.id.Button04:
// 检索一条特定的数据
db_ex.open();
Cursor c2 = db_ex.getTitle(2);
if (c2.moveToFirst()) {
DisplayTitle(c2);
} else {
Toast.makeText(this, "No title found", Toast.LENGTH_LONG)
.show();
}
db_ex.close();
break;
default:
break;
}
}
// 显示数据库中的所有数据
public void DisplayTitle(Cursor c) {
Toast.makeText(
this,
"id: " + c.getString(0) + "\n" + "ISBN: " + c.getString(1)
+ "\n" + "TITLE: " + c.getString(2) + "\n"
+ "PUBLISHER: " + c.getString(3), Toast.LENGTH_LONG)
.show();
}
}
|