SQLiteDatabase db;
Cursor cur;
SimpleCursorAdapter adapter;
// 打开或创建数据库
db = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
// 创建数据表
String createTable="CREATE TABLE IF NOT EXISTS " + TB_NAME +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + //索引字段
"name VARCHAR(32), " +
"phone VARCHAR(16), " +
"email VARCHAR(64))";
db.execSQL(createTable);
cur=db.rawQuery("SELECT * FROM "+ TB_NAME, null); // 查询数据
// 若查询结果是空的则写入 2 项测试数据
if(cur.getCount()==0){
addData("旗标公司","02-23963257","service@flag.com.tw");
addData("旗讯公司","02-23214335","service@pcdiy.com.tw");
}
adapter=new SimpleCursorAdapter(this,
R.layout.item, cur,
FROM,
new int[] {R.id.name,R.id.phone,R.id.email}, 0);
lv=(ListView)findViewById(R.id.lv);
lv.setAdapter(adapter); // 设置 Adapter
lv.setOnItemClickListener(this); // 设置单击事件的监听器
requery(); // 调用自定义方法, 重新查询及设置按钮状态
}
private void addData(String name, String phone, String email) {
ContentValues cv=new ContentValues(3); // 创建含 3 个字段的 ContentValues对象
cv.put(FROM[0], name);
cv.put(FROM[1], phone);
cv.put(FROM[2], email);
db.insert(TB_NAME, null, cv); // 新增1个记录
}
private void update(String name, String phone, String email, int id) {
ContentValues cv=new ContentValues(3);
cv.put(FROM[0], name);
cv.put(FROM[1], phone);
cv.put(FROM[2], email);
db.update(TB_NAME, cv, "_id="+id, null); // 更新 id 所指的字段
}
public void call(View v){ // 打电话
String uri="tel:" + cur.getString(
cur.getColumnIndex(FROM[1]));
Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(it);
}
public void mail(View v){ // 发送电子邮件
String uri="mailto:"+cur.getString(
cur.getColumnIndex(FROM[2]));
Intent it = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
startActivity(it);
}