import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DBHelper helper = null;
public static SQLiteDatabase db = null;
private static DBManager dbManager = null;
public DBManager(Context context) {
try {
helper = new DBHelper(context);
if (db == null)
db = helper.getWritableDatabase();
} catch (Exception e) {
return;
}
}
public static SQLiteDatabase getDB() {
return db;
}
public static DBManager getDBManager(Context context) {
if (dbManager == null)
dbManager = new DBManager(context);
return dbManager;
}
public void insert(String table, ContentValues cv) {
try {
if (db.isOpen())
db.insert(table, null, cv);
else {
db = helper.getWritableDatabase();
db.insert(table, null, cv);
}
} catch (Exception e) {
return;
}
}
public void delete(String sql) {
try {
if (db.isOpen())
db.execSQL(sql);
else {
db = helper.getWritableDatabase();
db.execSQL(sql);
}
} catch (Exception e) {
return;
}
}
public Cursor query(String sql) {
try {
if (db.isOpen()) {
Cursor cursor = db.rawQuery(sql, null);
return cursor;
} else {
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
return cursor;
}
} catch (Exception e) {
return null;
}
}
public boolean update(String table, ContentValues cv, String where, String[] arr) {
try {
if (db.isOpen())
db.update(table, cv, where, arr);
else {
db = helper.getWritableDatabase();
db.update(table, cv, where, arr);
}
return true;
} catch (Exception e) {
return false;
}
}
public void closdDB() {
try {
if (db != null) {
if (db.isOpen()) {
db.close();
}
}
} catch (Exception e) {
return;
}
}
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "mydb.db";
public static final String CHAT_TABLE = "mytable";
private static final int VERSION = 1;
private static final String TABLE_CREATE = "create table if not exists " + CHAT_TABLE +
"(" +
"id integer primary key autoincrement," +
"content text," +
"name text)";
public DBHelper(Context context){
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
try{
db.execSQL(TABLE_CREATE);
}catch(Exception e){
return;
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2){
}
}
ContentValues cv = new ContentValues();
cv.put("content","value1");
cv.put("name","jack");
DBManager.getDBManager(MainActivity.this).insert(DBHelper.CHAT_TABLE, cv);