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);
}