目前资料上greendao的删除基本都是根据主键删除的,如果我想通过里面一个字段比如name进行删除呢?下面是我对于全局搜索apk的一个greendao的小结。
1.删除某个字段的整条数据
简单封装下Greendao:
GreendaoUtil.java
public class GreendaoUtil {
private volatile static GreendaoUtil ourInstance;
private static String name = "search_history";
public static final String SQL_DISTINCT_ENAME = "SELECT DISTINCT " + SearchHistoryDao.Properties.Text.columnName + " FROM " + SearchHistoryDao.TABLENAME;
public static final String SQL_Delete = "DELETE FROM " + SearchHistoryDao.TABLENAME + " where text = ";
private Context mContetx;
private final DaoMaster mDaoMaster;
private final DaoSession mDaoSession;
public static GreendaoUtil getInstance() {
if (null == ourInstance) {
synchronized (GreendaoUtil.class) {
if (null == ourInstance) {
ourInstance = new GreendaoUtil();
}
}
}
return ourInstance;
}
private GreendaoUtil() {
this.mContetx = ZSApplication.getAppContext();
MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(mContetx, name, null);
mDaoMaster = new DaoMaster(mySQLiteOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
}
public DaoMaster getmDaoMaster() {
return mDaoMaster;
}
public DaoSession getmDaoSession() {
return mDaoSession;
}
}
注意上面的删除语句,使用的话:
GreendaoUtil.getInstance().getmDaoSession().getDatabase().execSQL(GreendaoUtil.SQL_Delete + mdeleteText);
其中 SQL_Delete中SearchHistoryDao.TABLENAME就是你的表名,text其实就是你的字段
这样就能删掉该条数据。
2.非主键去重插入
Cursor cursor = GreendaoUtil.getInstance().getmDaoSession().getDatabase().rawQuery(GreendaoUtil.SQL_DISTINCT_ENAME, null);
mHistoryList.clear();
try {
if (cursor.moveToFirst()) {
do {
mHistoryList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
} finally {
cursor.close();
}
利用这个去重,然后将最后的集合加入Recyclerview。