Skip to content

Instantly share code, notes, and snippets.

@allenatwork
Created September 8, 2016 10:47
Show Gist options
  • Save allenatwork/800da8feb798a497658ee456174daab3 to your computer and use it in GitHub Desktop.
Save allenatwork/800da8feb798a497658ee456174daab3 to your computer and use it in GitHub Desktop.
GreenDao
package biz.nadia.rola.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import biz.nadia.rola.dao.DaoMaster;
import biz.nadia.rola.dao.DaoSession;
import biz.nadia.rola.dao.RolaArticles;
import biz.nadia.rola.dao.RolaArticlesCache;
import biz.nadia.rola.dao.RolaArticlesCacheDao;
import biz.nadia.rola.dao.RolaArticlesDao;
import biz.nadia.rola.dao.RolaCategory;
import biz.nadia.rola.dao.RolaCategoryDao;
import biz.nadia.rola.dao.SearchHistory;
import biz.nadia.rola.dao.SearchHistoryDao;
import biz.nadia.rola.entities.Article;
import biz.nadia.rola.entities.ArticleCategory;
import de.greenrobot.dao.async.AsyncOperation;
import de.greenrobot.dao.async.AsyncOperationListener;
import de.greenrobot.dao.async.AsyncSession;
import de.greenrobot.dao.query.QueryBuilder;
/**
* Created by Allen on 04-Jul-16.
*/
public class DatabaseManager implements IDatabaseManager, AsyncOperationListener {
private static final String TAG = DatabaseManager.class.getCanonicalName();
private static final String TAG_CACHE = "RolaGreenCache";
public static final int CACHE_SIZE = 5;
public static final int SEARCH_CACHE_SIZE = 20;
private static DatabaseManager instance;
private Context context;
private DaoMaster.DevOpenHelper mHelper;
private SQLiteDatabase database;
private DaoMaster daoMaster;
private DaoSession daoSession;
private AsyncSession asyncSession;
private List<AsyncOperation> compdetedOperation;
public DatabaseManager(Context context) {
this.context = context;
mHelper = new DaoMaster.DevOpenHelper(this.context, "rola-database", null);
compdetedOperation = new CopyOnWriteArrayList<>();
}
public static DatabaseManager getInstance(Context context) {
if (instance == null) instance = new DatabaseManager(context);
return instance;
}
@Override
public void closeDbConnections() {
if (daoSession != null) {
daoSession.clear();
daoSession = null;
}
if (database != null && database.isOpen()) database.close();
if (mHelper != null) {
mHelper.close();
mHelper = null;
}
if (instance != null) instance = null;
}
@Override
public synchronized void dropDatabase() {
try {
openWritableDb();
DaoMaster.dropAllTables(database, true);
mHelper.onCreate(database);
asyncSession.delete(RolaArticles.class);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public synchronized Article addArticleToFavourite(Article article) {
RolaArticles dbArticle = new RolaArticles();
dbArticle.setArticle_id(article.getId());
dbArticle.setArticle_name(article.getName());
dbArticle.setAuthor_name(article.getAuthorNameList());
dbArticle.setSerie_title(article.getSeriesTitle());
dbArticle.setImage_path(article.getThumbnail());
insertArticletoFavourite(dbArticle);
addArticletoCache(article);
return null;
}
private RolaArticles insertArticletoFavourite(RolaArticles articles) {
if (articles == null) return null;
try {
openWritableDb();
RolaArticlesDao rolaArticlesDao = daoSession.getRolaArticlesDao();
rolaArticlesDao.insert(articles);
Log.d(TAG, "Insert Article with id " + articles.getArticle_id() + " into DB");
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
return articles;
}
@Override
public ArrayList<RolaArticles> getListArticles() {
List<RolaArticles> listArticle = null;
try {
openReadableDb();
RolaArticlesDao rolaArticlesDao = daoSession.getRolaArticlesDao();
listArticle = rolaArticlesDao.loadAll();
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
if (listArticle != null) return new ArrayList<>(listArticle);
return null;
}
@Override
public void deleteArticleById(int id) {
try {
openWritableDb();
Integer value = new Integer(id);
RolaArticlesDao articlesDao = daoSession.getRolaArticlesDao();
QueryBuilder<RolaArticles> query = articlesDao.queryBuilder().where(RolaArticlesDao.Properties.Article_id.eq(value));
List<RolaArticles> delList = query.list();
for (RolaArticles articles : delList) {
articlesDao.delete(articles);
Log.d(TAG, "Deleted artiles with id " + articles.getId() + " and article id " + articles.getArticle_id());
}
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void deleteArticleFromFav(Article article) {
deleteArticleById(article.getId());
removeArticlefromCache(article);
}
@Override
public ArticleCategory addCattoFav(ArticleCategory category) {
try {
openWritableDb();
RolaCategoryDao catDao = daoSession.getRolaCategoryDao();
RolaCategory rolaCategory = new RolaCategory();
rolaCategory.setAuthor_name(category.getAuthorNames());
rolaCategory.setCat_id(category.getId());
rolaCategory.setCat_name(category.getName());
rolaCategory.setCreate_date(category.getDate());
rolaCategory.setImg_path(category.getThumbnail());
catDao.insert(rolaCategory);
daoSession.clear();
Log.d(TAG, "Added category with Id " + category.getId() + " into database");
return category;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public ArrayList<RolaCategory> getListCategoryFav() {
List<RolaCategory> list = null;
try {
openReadableDb();
RolaCategoryDao catDao = daoSession.getRolaCategoryDao();
list = catDao.loadAll();
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
if (list != null) return new ArrayList<>(list);
return null;
}
@Override
public boolean isCatFollewed(ArticleCategory articleCategory) {
if (articleCategory == null) return false;
try {
openReadableDb();
RolaCategoryDao catDao = daoSession.getRolaCategoryDao();
List<RolaCategory> listCategory = catDao.loadAll();
for (RolaCategory cat : listCategory) {
if (articleCategory.getId() == cat.getCat_id()) {
daoSession.clear();
return true;
}
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public void deleteCatFromFav(ArticleCategory articleCategory) {
if (articleCategory == null) return;
try {
openWritableDb();
RolaCategoryDao catDao = daoSession.getRolaCategoryDao();
QueryBuilder<RolaCategory> query = catDao.queryBuilder().where(RolaCategoryDao.Properties.Cat_id.eq(articleCategory.getId()));
List<RolaCategory> listCat = query.list();
for (RolaCategory cat : listCat) {
catDao.delete(cat);
Log.d(TAG, "Removed category with Id " + cat.getCat_id() + " to database");
}
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onAsyncOperationCompleted(AsyncOperation operation) {
compdetedOperation.add(operation);
}
public void openReadableDb() throws SQLiteException {
database = mHelper.getReadableDatabase();
daoMaster = new DaoMaster(database);
daoSession = daoMaster.newSession();
asyncSession = daoSession.startAsyncSession();
asyncSession.setListener(this);
}
/**
* Query for writable DB
*/
public void openWritableDb() throws SQLiteException {
database = mHelper.getWritableDatabase();
daoMaster = new DaoMaster(database);
daoSession = daoMaster.newSession();
asyncSession = daoSession.startAsyncSession();
asyncSession.setListener(this);
}
public boolean checkIsFavouriteArtile(Article article) {
try {
openReadableDb();
RolaArticlesDao articlesDao = daoSession.getRolaArticlesDao();
QueryBuilder<RolaArticles> query = articlesDao.queryBuilder().where(RolaArticlesDao.Properties.Article_id.eq(article.getId()));
List<RolaArticles> listResult = query.list();
if (listResult == null || listResult.size() == 0) return false;
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// @Override
private void addArticletoCache(Article article) {
if (article == null) return;
Gson gson = new Gson();
String gsonString = gson.toJson(article);
try {
openWritableDb();
RolaArticlesCacheDao cacheDao = daoSession.getRolaArticlesCacheDao();
RolaArticlesCache cache = new RolaArticlesCache();
cache.setArticle_id(article.getId());
cache.setArticle_json(gsonString);
cacheDao.insert(cache);
Log.d(TAG_CACHE, "Save article withd id " + article.getId() + " to cache.");
keepCacheNotExceed(cacheDao);
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addSearchtoHistory(String key) {
if (TextUtils.isEmpty(key)) return;
try {
openWritableDb();
SearchHistoryDao searchDao = daoSession.getSearchHistoryDao();
delSearchKeyIfExits(searchDao, key);
SearchHistory searchHistory = new SearchHistory();
searchHistory.setSearch_key(key);
searchDao.insert(searchHistory);
keepSearchCacheNotExceed(searchDao, key);
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void delSearchHistory() {
try {
openWritableDb();
SearchHistoryDao searchHistoryDao = daoSession.getSearchHistoryDao();
searchHistoryDao.deleteAll();
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<SearchHistory> getListSearchHistory() {
try {
openReadableDb();
SearchHistoryDao searchDao = daoSession.getSearchHistoryDao();
List<SearchHistory> listHistory = searchDao.loadAll();
return listHistory;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void delSearchKeyIfExits(SearchHistoryDao searchDao, String key) {
QueryBuilder<SearchHistory> queryBuilder = searchDao.queryBuilder().where(SearchHistoryDao.Properties.Search_key.eq(key));
List<SearchHistory> listtoDel = queryBuilder.list();
if (listtoDel != null && listtoDel.size() > 0) {
for (SearchHistory history : listtoDel) {
searchDao.delete(history);
Log.d("Search History", "Del search word:" + history.getSearch_key() + ": because duplicate");
}
} else {
return;
}
}
private void keepSearchCacheNotExceed(SearchHistoryDao searchDao, String key) {
List<SearchHistory> listSearch = searchDao.loadAll();
if (listSearch != null && listSearch.size() > SEARCH_CACHE_SIZE) {
for (int i = 0; i < listSearch.size() - SEARCH_CACHE_SIZE; i++) {
searchDao.delete(listSearch.get(i));
Log.d("Search History", "Del search word:" + listSearch.get(i).getSearch_key() + ": because exceed");
}
}
}
// call just in addArticletoCache funtion. Otherwide, check database is open or not
private void keepCacheNotExceed(RolaArticlesCacheDao cacheDao) {
List<RolaArticlesCache> listCache = cacheDao.loadAll();
if (listCache.size() > CACHE_SIZE) {
for (int i = 0; i < listCache.size() - CACHE_SIZE; i++) {
removeArticleWithIdFromCache(listCache.get(i).getArticle_id());
}
}
}
// @Override
private void removeArticlefromCache(Article article) {
removeArticleWithIdFromCache(article.getId());
}
public boolean removeArticleWithIdFromCache(int articleId) {
try {
openWritableDb();
RolaArticlesCacheDao cacheDao = daoSession.getRolaArticlesCacheDao();
QueryBuilder<RolaArticlesCache> query = cacheDao.queryBuilder().where(RolaArticlesCacheDao.Properties.Article_id.eq(articleId));
List<RolaArticlesCache> listtoDel = query.list();
if (listtoDel != null && listtoDel.size() > 0)
for (RolaArticlesCache cache : listtoDel) {
cacheDao.delete(cache);
Log.d(TAG_CACHE, "Deleted cache of article " + articleId + " from cache");
}
else {
Log.d(TAG_CACHE, "The article with id " + articleId + " not exits in cache");
}
daoSession.clear();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// @Override
public Article getArticlefromCache(int artileId) {
try {
openReadableDb();
RolaArticlesCacheDao cacheDao = daoSession.getRolaArticlesCacheDao();
QueryBuilder<RolaArticlesCache> query = cacheDao.queryBuilder().where(RolaArticlesCacheDao.Properties.Article_id.eq(artileId));
List<RolaArticlesCache> listCache = query.list();
if (listCache != null && listCache.size() > 0) {
if (listCache.size() == 1) {
Article article = convertStringtoArticle(listCache.get(0).getArticle_json());
Log.d(TAG_CACHE, "CACHE HIT ! Article id " + artileId);
return article;
} else {
Article article = convertStringtoArticle(listCache.get(0).getArticle_json());
Log.d(TAG_CACHE, "CACHE HIT ! Mutiple cache found !!!");
return article;
}
} else {
Log.d(TAG_CACHE, "CACHE MISS ! Not found article withd id " + artileId + " in cache");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Article convertStringtoArticle(String json) {
if (TextUtils.isEmpty(json)) return null;
Gson gson = new Gson();
try {
Article article = gson.fromJson(json, Article.class);
return article;
} catch (JsonSyntaxException e) {
Log.d(TAG_CACHE, "Json invalid");
}
return null;
}
}
public class GreenDaoGenerator {
private static final String PROJECT_DIR = System.getProperty("user.dir").replace("\\", "/");
private static final String OUT_DIR = PROJECT_DIR + "/app/src/main/java";
public static void main(String args[]) throws Exception {
Schema schema = new Schema(1, "biz.nadia.rola.dao");
addTables(schema);
new DaoGenerator().generateAll(schema, OUT_DIR);
}
private static void addTables(Schema schema) {
// Enterty
Entity article = addArticles(schema);
Entity cache = addCache(schema);
Entity category = addCategory(schema);
Entity searchcache = addSearchCache(schema);
}
private static Entity addCategory(Schema schema) {
Entity cat = schema.addEntity("RolaCategory");
cat.addIdProperty().primaryKey().autoincrement();
cat.addIntProperty("cat_id").unique().notNull();
cat.addStringProperty("cat_name");
cat.addStringProperty("img_path");
cat.addStringProperty("author_name");
cat.addStringProperty("create_date");
return cat;
}
private static Entity addArticles(Schema schema) {
Entity article = schema.addEntity("RolaArticles");
article.addIdProperty().primaryKey().autoincrement();
article.addIntProperty("article_id").unique().notNull();
article.addStringProperty("article_name");
article.addStringProperty("serie_title");
article.addStringProperty("author_name");
article.addStringProperty("image_path");
return article;
}
private static Entity addCache(Schema schema) {
Entity cache = schema.addEntity("RolaArticlesCache");
cache.addIdProperty().primaryKey().autoincrement();
cache.addIntProperty("article_id").unique().notNull();
cache.addStringProperty("article_json");
return cache;
}
private static Entity addSearchCache(Schema schema) {
Entity searchCache = schema.addEntity("SearchHistory");
searchCache.addIdProperty().primaryKey().autoincrement();
searchCache.addStringProperty("search_key").notNull();
return searchCache;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment