初始化:
SqliteUtils.getVideoDao(context);
public class SqliteUtils {
private static final String TAG = "SqliteUtils";
private static DaoMaster daoMaster;
private static DaoSession daoSession;
private static VideoDao videoDao = null;
/**
* 取得DaoMaster
*
* @param context
* @return
*/
private static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "dbname", null);
SQLiteDatabase db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
L.i("create tvdb");
}
return daoMaster;
}
/**
* 取得DaoSession
*
* @param context
* @return
*/
public static void getVideoDao(Context context) {
if (videoDao == null) {
daoSession = getDaoSession(context);
videoDao = daoSession.getVideoDao();
} else {
videoDao = daoSession.getVideoDao();
}
}
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
/*
* 添加数据
*/
public static void setVideo(String name, String resolution, String url) {
Video video = new Video();
video.setName(name);
video.setResolution(resolution);
if (url.contains("?")){
url = url.split("\\?")[0];
}
video.setUrl(url);
videoDao.insert(video);
}
/**
* 获取数据
*
* @param url
* @return
*/
public static Video getVideo(String url) {
QueryBuilder<Video> buider = videoDao.queryBuilder();
Query<Video> query = buider.where(Properties.Url.eq(url)).orderDesc(Properties.Id).build();
query.forCurrentThread();
if (query.list().size() == 0) {
return null;
}
return query.list().get(0);
}
/**
* 获取所有数据大小
*
* @return
*/
public static int getVideoAll() {
QueryBuilder<Video> buider = videoDao.queryBuilder();
Query<Video> query = buider.build();
query.forCurrentThread();
return query.list().size();
}
/**
* 清理数据
*
* @param n
*/
public static void deleteVideo(int n) {
List<Video> allCustomers = rawQuery(n);
if (allCustomers.size() > 0) {
for (int i = 0; i < allCustomers.size(); i++) {
videoDao.delete(allCustomers.get(i));
}
}
}
private static List<Video> rawQuery(int n) {
return videoDao.queryRaw(" limit " + n + " offset 0 ");
}
/**
* 清空所有数据
*/
public static void deleteAll() {
videoDao.deleteAll();
}
}