1:需要一個輔助類
package com.dspsemi.im.receiver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "friend.db";
private static final String TBL_NAME = "friends";
public final static String CREATE_TBL = "create table friends( name varchar(20))";
private SQLiteDatabase db;
public DatabaseHelper(Context c) {
super(c, DB_NAME, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
db.execSQL(CREATE_TBL);
}
public void insert(ContentValues values) {
if (db == null) {
db = getWritableDatabase();
}
db.insert(TBL_NAME, null, values);
db.close();
}
public Cursor query() {
if (db == null)
db = getWritableDatabase();
Cursor c = db.query(TBL_NAME, null, null, null, null, null, null);
return c;
}
public void del(String nowtime) {
if (db == null) {
db = getWritableDatabase();
}
int temp = db.delete(TBL_NAME, "nowtime=? ", new String[] { nowtime });
System.out.print("delete result = " + temp);
}
public void close() {
if (db != null)
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// public Cursor execSql(String sql){
// Cursor c = db.execSQL(sql);
// }
}
二 就是調用方法
插入 和查詢
private void addFriend(String friendName) {
DatabaseHelper helper = new DatabaseHelper(MainActivity.this);
try {
ContentValues values = new ContentValues();
values.put("name", friendName);
helper.insert(values);
} catch (Exception e) {
} finally {
helper.close();
}
}
private void queryFriend() {
DatabaseHelper dh = new DatabaseHelper(this);
Cursor cur = dh.query();
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
String nametemp = cur.getString(cur.getColumnIndex("name"));
// Log.i("test", "naem" + nametemp);
FriendNameList.add(nametemp);
}
mHandler.sendEmptyMessage(54);
}