1、数据库封装工具类
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBTools {
public static void insert(Context context, DownloadInfoBean bean){
DBHelper db = new DBHelper(context);
db.open();
db.insert(bean);
db.close();
}
public static void delete(Context context){
DBHelper db = new DBHelper(context);
db.open();
db.delete();
db.close();
}
public static void update(Context context, DownloadInfoBean bean){
DBHelper db = new DBHelper(context);
db.open();
db.update(bean);
db.close();
}
public static DownloadInfoBean query(Context context){
DownloadInfoBean bean = null;
DBHelper db = new DBHelper(context);
db.open();
Cursor cursor = db.query();
if(cursor != null){
if(cursor.getCount() > 0){
cursor.moveToFirst();
bean = new DownloadInfoBean();
bean.filesize = cursor.getInt(1);
bean.complete = cursor.getInt(2);
}
cursor.close();
}
db.close();
return bean;
}
public static final class DBHelper extends SQLiteOpenHelper{
private final static String DB_NAME = "download_info.db";
private final static int DB_VERSION = 1;
private final String TB_DOWNLOAD_INFO = "tb_download_info";
private static SQLiteDatabase sqlDb = null;
private static Object lock = new Object();
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// TODO Auto-generated constructor stub
}
public void open(){
synchronized (lock) {
sqlDb = this.getReadableDatabase();
}
}
public void close(){
synchronized (lock) {
if(sqlDb != null){
sqlDb.close();
}
}
}
public void insert(DownloadInfoBean bean){
synchronized (lock) {
ContentValues values = new ContentValues();
values.put("filesize", bean.filesize);
values.put("complete", bean.complete);
sqlDb.insert(TB_DOWNLOAD_INFO, null, values);
}
}
public void delete(){
synchronized (lock) {
sqlDb.delete(TB_DOWNLOAD_INFO, null, null);
}
}
public void update(DownloadInfoBean bean){
synchronized (lock) {
ContentValues values = new ContentValues();
values.put("complete", bean.complete);
sqlDb.update(TB_DOWNLOAD_INFO, values, "filesize=?", new String[]{bean.filesize+""});
}
}
public Cursor query(){
synchronized (lock) {
return sqlDb.query(TB_DOWNLOAD_INFO, null, null, null, null, null, null);
}
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE IF NOT EXISTS "+
TB_DOWNLOAD_INFO+"("+
"id integer NOT NULL PRIMARY KEY AUTOINCREMENT,"+
"filesize integer NOT NULL default 0,"+//文件大小
"complete integer NOT NULL default 0)");//下载完成大小
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
onCreate(db);
}
}
}
2、数据对象bean
public class DownloadInfoBean {
public int filesize = 0;
public int complete = 0;
}
原创内容转载请保留出处GEEK笔记(https://www.geekapp.cn/)。