Greendao的根据某个字段(非主键)插入去重以及根据某个字段删除对应的行条目

目前资料上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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值