Android 简单使用 GreenDao3.0

GreenDao的使用

 1、在project的build.grade文件中添加如下依赖

     classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'

 2、在app的build.grade文件中添加如下依赖

     compile 'org.greenrobot:greendao:3.0.1'
     compile 'org.greenrobot:greendao-generator:3.0.0'

3、在app的build.gradle文件中声明greendao的路径、版本、名称的设置

     greendao {
    schemaVersion 1
    daoPackage 'com.zty.greendao.gen'
    targetGenDir 'src/main/java'
    }

4、在app的build.gradle文件中顶部添加

    apply plugin: 'org.greenrobot.greendao'

5、创建实体类

@Entity
public class Equip implements java.io.Serializable {
    @Id
    @Property(nameInDb = "EQUIP_ID")
    private Long equipId;

    private Long roomId;

    private Integer organId;
    private Integer equipTypeId;

    private String cardNo;

    private String equipName;

    private String equipSpecify;

    private String equipBrand;

    private Integer count;

    private String assetCode;

    private Integer assetTypeId;

    private String assetSource;

    private Long userId;

    private String userName;

    private String remark;
    @Transient
    private Integer newDataFlag;

}

6、创建完实体类后点击android studio中的如下图标

7、点击如上图标后会生成如下几个代码

Android 简单使用 GreenDao3.0_第1张图片

8、以下我们将在Application配置数据库的一些参数就可以使用了

private DbManager manager;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
@Override    public void onCreate() {
    super.onCreate();
    
    setDatabase();

 }

private void setDatabase() {
    manager=new DbManager(this, "collect-db");
    db = manager.getWritableDatabase();
    // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
    mDaoMaster = new DaoMaster(db);
    mDaoSession = mDaoMaster.newSession();

}
public static MyApplication getInstances(){
    return instances;

}

public DaoSession getDaoSession() {
    return mDaoSession;
}

9、配置好后我们可以按下面方法调用

 

 DaoSession daoSession= MyApplication.getInstances().getDaoSession();
List equips=daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.RoomId.eq(roomId))
.list();

至此最简单的数据库查询已经完成

10、部分数据库查询代码如下

public class DataUtil {
    private static String root= Environment.getExternalStorageDirectory().getPath();
    private static DaoSession daoSession= MyApplication.getInstances().getDaoSession();

    /**
     * 根据设备获取图片
     * @param context
     * @param organId
     * @param equipId
     * @return
     */
    public static List> getImageByEquipId(Context context, Long organId, Long equipId) {
        //根据 organId 为目录 每个学校有个文件目录
        List list=new ArrayList();
        List attachments=daoSession.getAttachmentDao().queryBuilder().where(AttachmentDao.Properties.BizId.eq(equipId)).list();
        for (Attachment attachment:attachments){
            HashMap map=new HashMap();
            File file=getSchoolPathByOrganId(organId,attachment.getFileName());
            //文件地址
            map.put("url",file.getPath());
            map.put("view",new ImageView(context));
            list.add(map);

        }
        return list;
    }

    /**
     * 根据模板设备id获取模板图片
     * @param context
     * @param modelEquipId
     * @return
     */
    public static List> getImageByModelEquipId(Context context, Long modelEquipId) {
        //根据 organId 为目录 每个学校有个文件目录
        List list=new ArrayList();
        List modelEquipAttachMents=daoSession.getModelEquipAttachMentDao()
                .queryBuilder().where(ModelEquipAttachMentDao.Properties.ModelEquipId.eq(modelEquipId)).list();
        for (ModelEquipAttachMent ModelEquipAttachMent:modelEquipAttachMents){
            HashMap map=new HashMap();
            File file=getSchoolPathByModel("model",ModelEquipAttachMent.getFileName());
            //文件地址
            map.put("url",file.getPath());
            map.put("view",new ImageView(context));
            list.add(map);
        }
        return list;
    }

    /**
     * 根据学校id获取学校路径
     * @param organId
     * @param fileName
     * @return
     */
    public static File getSchoolPathByOrganId(Long organId, String fileName) {
        File dir=new File(root,MyApplication.getInstances().getPrjName());
        File schoolDir=new File(dir.getPath(),organId+"");
        if(!schoolDir.exists()){
            schoolDir.mkdirs();
        }
        File file=new File(schoolDir.getPath(),fileName);
        return file;
    }

    /**
     * 根据学校id获取学校目录
     * @param organId
     * @return
     */
    public static File getSchoolPathByOrganIdDir(Long organId) {
        File dir=new File(root,MyApplication.getInstances().getPrjName());
        File schoolDir=new File(dir.getPath(),organId+"");
        if(!schoolDir.exists()){
            schoolDir.mkdirs();
        }
        return schoolDir;
    }
    public static File getCompressFile() {
        File dir=new File(root,MyApplication.getInstances().getPrjName());
        File compressDir=new File(dir.getPath(),"compress");
        return compressDir;
    }
    private static File getSchoolPathByModel(String model, String fileName) {
        File dir=new File(root,MyApplication.getInstances().getPrjName());
        File schoolDir=new File(dir.getPath(),model+"");
        if(!schoolDir.exists())
            schoolDir.mkdirs();
        File file=new File(schoolDir.getPath(),fileName);
        return file;
    }
    public static List getSchoolData(Context context) {
        List mSortList=new ArrayList<>();
        List organs=daoSession.getOrganDao().queryBuilder().list();
        Log.i("ggg","getSchoolData size="+organs.size());
        for (int i = 0; i < organs.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(organs.get(i).getOrganName());
            sortModel.setBizId(organs.get(i).getOrganId());
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(organs.get(i).getOrganName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式,判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);
        }

        return mSortList;
    }

    public static List getRoomData(RoomActivity roomActivity, Long organId, String inventoryStatus,Long blockId,Integer cnt) {
        List mSortList=new ArrayList<>();
        List rooms=null;
        if("".equals(inventoryStatus)){
             rooms=daoSession.getRoomDao().queryBuilder()
                    .where(RoomDao.Properties.OrganId.eq(organId))
                     .where(RoomDao.Properties.BlockId.eq(blockId))
                     .where(RoomDao.Properties.Floor.eq(cnt))
                     .list();
        }else if("0".equals(inventoryStatus)){
            //如果 inventoryStatus等于 0  数据库中默认未 null 和 0 表示为未操作
             rooms=daoSession.getRoomDao().queryBuilder()
                    .whereOr(RoomDao.Properties.InventoryStatus.eq(inventoryStatus),RoomDao.Properties.InventoryStatus.isNull())
                    .where(RoomDao.Properties.OrganId.eq(organId))
                     .where(RoomDao.Properties.BlockId.eq(blockId))
                     .where(RoomDao.Properties.Floor.eq(cnt))
                     .list();
        }else{
            rooms=daoSession.getRoomDao().queryBuilder()
                    .where(RoomDao.Properties.InventoryStatus.eq(inventoryStatus))
                    .where(RoomDao.Properties.OrganId.eq(organId))
                    .where(RoomDao.Properties.BlockId.eq(blockId))
                    .where(RoomDao.Properties.Floor.eq(cnt))
                    .list();
        }

        Log.i("ggg","getSchoolData size="+rooms.size());
        for (int i = 0; i < rooms.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(rooms.get(i).getRoomName());
            sortModel.setBizId(rooms.get(i).getRoomId());
            sortModel.setRoomNo(rooms.get(i).getRoomNo());
            sortModel.setInventoryStatus(rooms.get(i).getInventoryStatus());
            //汉字转换成拼音


            String pinyin = PinyinUtils.getPingYin(rooms.get(i).getRoomName());
            String sortString="";
            if(!"".equals(rooms.get(i).getRoomName())){
                 sortString = pinyin.substring(0, 1).toUpperCase();
            }
            // 正则表达式,判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);
        }

        return mSortList;
    }
    public static List getModelData(ModelListActivity modelListActivity) {
        List mSortList=new ArrayList<>();
        List models=daoSession.getModelDao().queryBuilder()
                .list();
        for (int i = 0; i < models.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(models.get(i).getModelName());
            sortModel.setBizId(models.get(i).getModelId());
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(models.get(i).getModelName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式,判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }
    public static List getModelEquipData(ModelDetailActivity modelDetailActivity, Long modelId) {
        List mSortList=new ArrayList<>();
        List modelEquips=daoSession.getModelEquipDao().queryBuilder()
                .where(ModelEquipDao.Properties.ModelId.eq(modelId))
                .list();
        for (int i = 0; i < modelEquips.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(modelEquips.get(i).getEquipName());
            sortModel.setBizId(modelEquips.get(i).getModelEquipId());
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(modelEquips.get(i).getEquipName());

            String sortString="";
            if(!"".equals(modelEquips.get(i).getEquipName())){
                 sortString = pinyin.substring(0, 1).toUpperCase();
            }
            // 正则表达式,判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;
    }
    public static List getEquipData(Context context, Long roomId, Long organId) {
        List mSortList=new ArrayList<>();
        List equips=daoSession.getEquipDao().queryBuilder()
                .where(EquipDao.Properties.RoomId.eq(roomId))
                .where(EquipDao.Properties.OrganId.eq(organId))
                .orderDesc(EquipDao.Properties.EquipId)
                .list();

        for (int i = 0; i < equips.size(); i++) {
            List attachments=daoSession.getAttachmentDao().queryBuilder()
                    .where(AttachmentDao.Properties.BizId.eq(equips.get(i).getEquipId())).list();
            SortModel sortModel = new SortModel();
            sortModel.setName(equips.get(i).getEquipName());
            sortModel.setBizId(equips.get(i).getEquipId());
            sortModel.setCount(String.valueOf(equips.get(i).getCount()));
            if(attachments.size()>0){
                File file=getSchoolPathByOrganId(organId,attachments.get(0).getFileName());
                //文件地址
                sortModel.setImageUrl(file.getPath());
            }
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(equips.get(i).getEquipName());
            String sortString = "";
            if("".equals(equips.get(i).getEquipName())){
                 sortString = "";
            }else{
                 sortString = pinyin.substring(0, 1).toUpperCase();
            }

            // 正则表达式,判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);

        }
            return mSortList;
    }
    public static Room getRoomById(Long roomId) {
        return daoSession.getRoomDao().queryBuilder().where(RoomDao.Properties.RoomId.eq(roomId)).unique();
    }

    public static String getOrganNameById(Long organId) {
        Organ organ=daoSession.getOrganDao().queryBuilder().where(OrganDao.Properties.OrganId.eq(organId)).unique();
        if(organ!=null){
            return organ.getOrganName();
        }
        return "";
    }

    public static String getRoomNameById(Long roomId) {
        Room room=daoSession.getRoomDao().queryBuilder().where(RoomDao.Properties.RoomId.eq(roomId)).unique();
        if(room!=null){
            return room.getRoomName();
        }
        return "";
    }

    public static Equip getEquipById(Long equipId) {
        return daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.EquipId.eq(equipId)).unique();
    }

    public static HashMap saveAttachMent(Long equipId, String fileName, Long organId,Context context) {
        Attachment attachment=new Attachment();
        attachment.setAttachmentId(KeyUtil.getUniqueKey());
        attachment.setBizId(equipId);
        attachment.setBizCode(organId+"");
        attachment.setCreateTime(Util.getNow());
        attachment.setNewDataFlag(1);
        attachment.setIsUpload(1);
        attachment.setFileName(fileName);
        attachment.setStatus(1);
        attachment.setRemark("");
        daoSession.getAttachmentDao().insert(attachment);
        HashMap map=new HashMap();
        File file=getSchoolPathByOrganId(organId,attachment.getFileName());
        //文件地址
        map.put("url",file.getPath());
        map.put("view",new ImageView(context));
        return map;
    }
    public static HashMap saveModelAttachMent(Long equipId, String fileName,Context context) {
        ModelEquipAttachMent attachment=new ModelEquipAttachMent();
       attachment.setAttachMentId(KeyUtil.getUniqueKey());
        attachment.setCreateTime(Util.getNow());
        attachment.setIsUpload(1);
        attachment.setFileName(fileName);
        attachment.setStatus(1);
        attachment.setModelEquipId(equipId);
        daoSession.getModelEquipAttachMentDao().insert(attachment);
        HashMap map=new HashMap();
        File file=getSchoolPathByModel("model",attachment.getFileName());
        //文件地址
        map.put("url",file.getPath());
        map.put("view",new ImageView(context));
        return map;
    }
    public static void saveEquipModel(String name, List equips, Long organId) {
        //生成模板
        Model model=new Model();
        model.setModelName(name);
        model.setModelId(KeyUtil.getUniqueKey());
        Long modelId=daoSession.getModelDao().insert(model);
        //插入模板装备
        //获取所有装备
        for(Equip equip:equips){
            ModelEquip modelEquip=new ModelEquip();
            modelEquip.setEquipName(equip.getEquipName());
            modelEquip.setEquipBrand(equip.getEquipBrand());
            modelEquip.setEquipSpecify(equip.getEquipSpecify());
            modelEquip.setModelId(modelId);
            modelEquip.setModelEquipId(KeyUtil.getUniqueKey());
            Long modelEquipId=daoSession.getModelEquipDao().insert(modelEquip);
            //将装备转为模板
            List attachments=daoSession.getAttachmentDao().queryBuilder().where(AttachmentDao
            .Properties.BizId.eq(equip.getEquipId())).list();
            //将装备复制到模板数据
            for(Attachment attachment:attachments){
                String modelName=KeyUtil.getFileName();
                File newFile=getSchoolPathByModel("model",modelName);
                File oldFile=getSchoolPathByOrganId(organId,attachment.getFileName());
                if(Util.copyFile(oldFile,newFile)){
                    ModelEquipAttachMent modelEquipAttachMent=new ModelEquipAttachMent();
                    modelEquipAttachMent.setModelEquipId(modelEquipId);
                    modelEquipAttachMent.setCreateTime(Util.getNow());
                    modelEquipAttachMent.setFileName(modelName);
                    modelEquipAttachMent.setAttachMentId(KeyUtil.getUniqueKey());
                    modelEquipAttachMent.setIsUpload(1);
                    modelEquipAttachMent.setStatus(1);
                    daoSession.getModelEquipAttachMentDao().insert(modelEquipAttachMent);
                }
            }
        }
    }

    public static ModelEquip getModelEquipById(Long modelEquipId) {
        return daoSession.getModelEquipDao().queryBuilder().where(ModelEquipDao.Properties.ModelEquipId.eq(modelEquipId)).unique();
    }
    public static List getModelList(Context context) {
        List models=daoSession.getModelDao().queryBuilder().list();
        return models;
    }

    public static void deleteEquipById( Long bizId,Long organId) {
        //先删除子表再删除主表
        try {
            List attachments=daoSession.getAttachmentDao().queryBuilder().where(AttachmentDao.Properties.BizId.eq(bizId)).list();
            for (Attachment attachment:attachments){
                File file=getSchoolPathByOrganId(organId,attachment.getFileName());
                daoSession.getAttachmentDao().delete(attachment);
                if(file.exists()&&file.isFile())
                    file.delete();
            }
            daoSession.getEquipDao().deleteByKey(bizId);
        }catch (Exception e){

        }

    }
    public static void deleteModelEquipById(Long bizId) {

        try {
            List modelEquipAttachMents=daoSession.getModelEquipAttachMentDao()
                    .queryBuilder().where(ModelEquipAttachMentDao.Properties.ModelEquipId.eq(bizId)).list();
            for (ModelEquipAttachMent ModelEquipAttachMent:modelEquipAttachMents){
                daoSession.getModelEquipAttachMentDao().delete(ModelEquipAttachMent);
                File file=getSchoolPathByModel("model",ModelEquipAttachMent.getFileName());
                if(file.exists()&&file.isFile())
                    file.delete();
            }
            daoSession.getModelEquipDao().deleteByKey(bizId);
        }catch (Exception e){

        }


    }
    public static void saveEquipByModelId(Long modelId, Long roomId, Long organId,Context context) {
        List modelEquips=daoSession.getModelEquipDao().queryBuilder()
                .where(ModelEquipDao.Properties.ModelId.eq(modelId)).list();
        Log.i("ggg","saveEquipByModelId"+modelEquips.size());
        for (ModelEquip modelEquip:modelEquips){
            Equip  equip=new Equip();
            equip.setEquipId(KeyUtil.getUniqueKey());
            equip.setEquipName(modelEquip.getEquipName());
            equip.setEquipBrand(modelEquip.getEquipBrand());
            equip.setEquipSpecify(modelEquip.getEquipSpecify());
            equip.setUserId(DataUtil.getCurrentUserId(context));
            equip.setCount(1);
            equip.setCardNo("");
            equip.setUserName("");
            equip.setRemark("");
            equip.setOrganId(organId.intValue());
            equip.setRoomId(roomId);
            Long equipId=MyApplication.getInstances().getDaoSession().getEquipDao().insert(equip);

            List attachMents=daoSession.getModelEquipAttachMentDao().queryBuilder()
                    .where(ModelEquipAttachMentDao.Properties.ModelEquipId.eq(modelEquip.getModelEquipId())).list();
            for (ModelEquipAttachMent attachMent:attachMents){
                //kk
                //先复制文件 然后复制数据
                File file=getSchoolPathByModel("model",attachMent.getFileName());
                String name=KeyUtil.getFileName();
                String fileName=DataUtil.getOrganNameById(organId)+"_"+DataUtil.getRoomNameById(roomId)+"_"+name;
                File newFile=getSchoolPathByOrganId(organId,fileName);
                if(Util.copyFile(file,newFile)){
                    Attachment attachment=new Attachment();
                    attachment.setAttachmentId(KeyUtil.getUniqueKey());
                    attachment.setBizId(equipId);
                    attachment.setBizCode(organId+"");
                    attachment.setCreateTime(Util.getNow());
                    attachment.setNewDataFlag(1);
                    attachment.setIsUpload(1);
                    attachment.setFileName(fileName);
                    attachment.setStatus(1);
                    attachment.setRemark("");
                    daoSession.getAttachmentDao().insert(attachment);
                }
            }
            //同时将图片复制出来
        }
    }
    public static Model getModelById(Long modelId) {
        return daoSession.getModelDao().queryBuilder().where(ModelDao.Properties.ModelId.eq(modelId)).unique();
    }

    public static void updateEquipById(SortModel sortModel) {
        Equip equip=daoSession.getEquipDao().queryBuilder()
                .where(EquipDao.Properties.EquipId.eq(sortModel.getBizId())).unique();
        if(equip!=null){
            equip.setCount(Integer.valueOf(sortModel.getCount()));
            daoSession.getEquipDao().update(equip);
        }
    }
    public static void saveLoginUser(String json, Context context)throws JSONException {
        JSONObject jsonObject=new JSONObject(json);
        int userId=jsonObject.getInt("userId");
        UserInfo searchUser=daoSession.getUserInfoDao().queryBuilder()
                .where(UserInfoDao.Properties.UserId.eq(userId)).unique();
        if(searchUser==null){
            UserInfo user=new UserInfo();
            user.setUserId(Long.valueOf(userId));
            daoSession.getUserInfoDao().insert(user);

        }else{
            searchUser.setUserId(Long.valueOf(userId));
            daoSession.getUserInfoDao().update(searchUser);
        }
        SPUtils.put(context,ConfigUtil.CURRENT_USER_ID,userId);
    }

    public static List getDataByOrganId(Long organId) {
        List objects=new ArrayList<>();
        Gson gson=new Gson();
        //房间
        List rooms=daoSession.getRoomDao().queryBuilder().where(RoomDao.Properties.OrganId.eq(organId))
//                .where(RoomDao.Properties.NewDataFlag.eq(1))
                .list();
        String roomStr=gson.toJson(rooms);
        List roomList = gson.fromJson(roomStr,
                new TypeToken>() {
                }.getType());

        objects.addAll(roomList);
//        Log.i("ggg",roomList.get(0).getBlockId()+"");


        //装备
        List equips=daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.OrganId.eq(organId))
//                .where(EquipDao.Properties.NewDataFlag.eq(1))
                .list();
        String equipStr=gson.toJson(equips);
        List equipList = gson.fromJson(equipStr,
                new TypeToken>() {
                }.getType());
        objects.addAll(equipList);
     // 文件
        for(Equip equip:equips){
            List attachments=daoSession.getAttachmentDao().
                    queryBuilder()
//                    .where(AttachmentDao.Properties.NewDataFlag.eq(1))
                    .where(AttachmentDao.Properties.BizId.eq(equip.getEquipId())).list();

            String fileStr=gson.toJson(attachments);
            List attachmentList = gson.fromJson(fileStr,
                    new TypeToken>() {
                    }.getType());

            objects.addAll(attachmentList);
        }
        //楼栋表
        List blocks=daoSession.getBlockDao().queryBuilder().where(BlockDao.Properties.OrganId.eq(organId))
                .list();
        String blockStr=gson.toJson(blocks);
        List blockList = gson.fromJson(blockStr,
                new TypeToken>() {
                }.getType());

        objects.addAll(blockList);
        return  objects;
    }
    public static List getDataByRoomId(Long roomId) {
        List objects=new ArrayList<>();
        Gson gson=new Gson();

        //装备
        List equips=daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.RoomId.eq(roomId))
//                .where(EquipDao.Properties.NewDataFlag.eq(1))
                .list();
        String equipStr=gson.toJson(equips);
        List equipList = gson.fromJson(equipStr,
                new TypeToken>() {
                }.getType());
        objects.addAll(equipList);
        // 文件
        for(Equip equip:equips){
            List attachments=daoSession.getAttachmentDao().
                    queryBuilder()
//                    .where(AttachmentDao.Properties.NewDataFlag.eq(1))
                    .where(AttachmentDao.Properties.BizId.eq(equip.getEquipId())).list();

            String fileStr=gson.toJson(attachments);
            List attachmentList = gson.fromJson(fileStr,
                    new TypeToken>() {
                    }.getType());

            objects.addAll(attachmentList);
        }

        return  objects;
    }
    public static List getAttachmentByOrganId(Long organId) {
        List attachments=new ArrayList<>();
        List equips=daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.OrganId.eq(organId)).list();
        for(Equip equip:equips){
            List singleAttachments=daoSession.getAttachmentDao().
                    queryBuilder().where(AttachmentDao.Properties.BizId.eq(equip.getEquipId()))
                    .where(AttachmentDao.Properties.IsUpload.eq(1))
                    .list();
            attachments.addAll(singleAttachments);
        }
        return  attachments;
    }
    public static List getAttachmentByRoomId(Long roomId) {
        List attachments=new ArrayList<>();
        List equips=daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.RoomId.eq(roomId)).list();
        for(Equip equip:equips){
            List singleAttachments=daoSession.getAttachmentDao().
                    queryBuilder().where(AttachmentDao.Properties.BizId.eq(equip.getEquipId()))
                    .where(AttachmentDao.Properties.IsUpload.eq(1))
                    .list();
            attachments.addAll(singleAttachments);
        }
        return  attachments;
    }
    public static Long getCurrentUserId(Context context) {
        int currentId= (int) SPUtils.get(context,ConfigUtil.CURRENT_USER_ID,-1);
       return Long.valueOf(currentId);
    }

    public static String getcurrentUserName(Context context) {
        String name= (String) SPUtils.get(context,ConfigUtil.CURRENT_USER_NAME,"");
        return name;
    }

    public static List getTask(Context context) {
        List sortModels=new ArrayList<>();
        String sql="select organ.organ_name,count(organ.organ_id) as cnt from organ,task where organ.organ_id=task.organ_id and task.send_type=1 and task.organ_id > ? group by task.organ_id  ";
        Cursor cursor=MyApplication.getInstances().getDb().rawQuery(sql,new String[] {"0"});
        while (cursor.moveToNext()){
            SortModel sortModel=new SortModel();
            String name=cursor.getString(0);
            int cnt=cursor.getInt(1);
            sortModel.setName(name);
            sortModel.setCount(cnt+"");
            sortModels.add(sortModel);
        }
        return sortModels;
    }
    public static List getDownTask(Context context) {
        List sortModels=new ArrayList<>();
        String sql="select organ.organ_name,count(organ.organ_id) as cnt from organ,task where organ.organ_id=task.organ_id and task.send_type=2 and task.organ_id > ? group by task.organ_id  ";
        Cursor cursor=MyApplication.getInstances().getDb().rawQuery(sql,new String[] {"0"});
        while (cursor.moveToNext()){
            SortModel sortModel=new SortModel();
            String name=cursor.getString(0);
            int cnt=cursor.getInt(1);
            sortModel.setName(name);
            sortModel.setCount(cnt+"");
            sortModels.add(sortModel);
        }
        return sortModels;
    }
    public static List getAttachmentByEquipId(Long equipId) {
        return daoSession.getAttachmentDao().queryBuilder().where(AttachmentDao.Properties.BizId.eq(equipId)).list();
    }
    public static List getModelAttachmentByEquipId(Long equipId) {
        return daoSession.getModelEquipAttachMentDao().queryBuilder().where(ModelEquipAttachMentDao.Properties.ModelEquipId.eq(equipId)).list();
    }

    public static Attachment getAttamentById(Long attachmentId) {
        return daoSession.getAttachmentDao().queryBuilder().where(AttachmentDao.Properties.AttachmentId.eq(attachmentId)).unique();
    }

    public static void deleteModelById(Long bizId) {
        daoSession.getModelDao().deleteByKey(bizId);

    }


    public static boolean isEmtyEquip(Long equipId) {
        Equip equip =getEquipById(equipId);
        List attachments=DataUtil.getAttachmentByEquipId(equipId);
        if(equip==null)
            return false;
        if("".equals(equip.getEquipName())&&attachments.size()==0){
            return true;
        }
        return false;
    }

    public static void showToast(final String s, final MainActivity mainActivity) {
        mainActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mainActivity, s, Toast.LENGTH_LONG).show();
            }
        });
    }


    private static Toast mToast = null;
    public static void showToast(Context context, String text, int duration) {
        if (mToast == null) {
            mToast = Toast.makeText(context, text, duration);
        } else {
            mToast.setText(text);
            mToast.setDuration(duration);
        }

        mToast.show();
    }

    public static void insertTask(Long userId, Long roomId,Long organId,Context context) {
        //将任务加入任务列表
        HashMap map;
        if(userId!=null&&userId!=-1L&&roomId==null){
            //说明获取用户的所有资产信息
            map=new HashMap();
            map.put("USER_ID",userId+"");
            map.put("ORGAN_ID",organId+"");
            SendClient.getInstance().sendOnlineInfo(1, map, null, organId,2);
        }else{
            //说明获取房间中的所有资产信息
                map=new HashMap();
                map.put("ROOM_ID",roomId+"");
                map.put("ORGAN_ID",organId+"");
                SendClient.getInstance().sendOnlineInfo(1, map, null, organId,2);

        }
    }

    public static String getRoomJson(Context roomActivity, Long organId) {
        Gson gson=new Gson();
        //房间
        List rooms=daoSession.getRoomDao().queryBuilder().where(RoomDao.Properties.OrganId.eq(organId))
                .where(RoomDao.Properties.NewDataFlag.eq(1))
                .list();
        String roomStr=gson.toJson(rooms);
        return roomStr;
    }

    public static void outDb(Context context) {
        String DATABASE_NAME = "collect-db";
        String oldPath = "data/data/com.zty.collectmanager/databases/" + DATABASE_NAME;
        File dir=new File(root,MyApplication.getInstances().getPrjName());
        String newPath = dir.getPath() + File.separator + DATABASE_NAME;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            File newfile = new File(newPath);
            if (!newfile.exists()) {
                newfile.createNewFile();
            }
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }

    public static void deleteImageByOrganId(Long organId) {
        File dir=new File(root,MyApplication.getInstances().getPrjName());
        File schoolDir=new File(dir.getPath(),organId+"");
        Log.i("ggg","deleteImageByOrganId "+schoolDir.getPath());
        if(schoolDir.exists()&&schoolDir.isDirectory()){
            String[] tempList = schoolDir.list();
            for (String f:tempList){
                File file=new File(f);
                file.delete();
            }
            schoolDir.delete();
        }
    }

    public static Block getBlockById(Long blockId) {
        return daoSession.getBlockDao().queryBuilder().where(BlockDao.Properties.BlockId.eq(blockId)).unique();
    }

    public static HashMap getBuild(Long organId) {
        HashMap result=new HashMap();
        try {
            //1 创建1级标题
            List gruops =daoSession.getBlockDao().queryBuilder().where(BlockDao.Properties.OrganId.eq(organId)).list();
            // 2 创业标题对应的子标题
            List>> childs = new ArrayList>>();
            for(Block block:gruops){
                List> child = new ArrayList>();
                //根据数量 将数字转换为层数
                Integer count=block.getLayerCnt();
                while (count> 0){
                    //如 count等于6 将数字拆成 1 2 3 4 5 6 根据层数 跟block id 找出房间
                    List rooms=daoSession.getRoomDao().queryBuilder().where(RoomDao.Properties.Floor.eq(count))
                            .where(RoomDao.Properties.BlockId.eq(block.getBlockId())).list();
                    Map temp = new HashMap();
                    temp.put("child", toChinese(String.valueOf(count))+" 层");
                    temp.put("count", rooms.size()+" 间");
                    temp.put("LAYER_CNT", count+"");
                    temp.put("BLOCK_ID", String.valueOf(block.getBlockId()));
                    count--;
                    child.add(temp);
                }
                childs.add(child);
            }
            result.put("group",gruops);
            result.put("child",childs);

        }catch (Exception e){
        }
        return result;
    }
    public static String toChinese(String string) {
        String[] s1 = { "", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };
        String result = "";
        int n = string.length();
        for (int i = 0; i < n; i++) {
            int num = string.charAt(i) - '0';
            if (i != n - 1 && num != 0) {
                result += s1[num] + s2[n - 2 - i];
            } else {
                result += s1[num];
            }
        }
        return result;
    }

    public static String getBlockNameById(Long blockId) {
        Block block=daoSession.getBlockDao().queryBuilder().where(BlockDao.Properties.BlockId.eq(blockId)).unique();
        if(block!=null){
            return block.getBlockName();
        }
        return "";
    }

    public static void deleteBlockById(String block_id) {
        daoSession.getBlockDao().deleteByKey(Long.valueOf(block_id));
    }

    public static void removeRoomById(Long roomId) {
        daoSession.getRoomDao().deleteByKey(roomId);

    }

    public static boolean exitAsset(Long roomId) {
        List equips=daoSession.getEquipDao().queryBuilder().where(EquipDao.Properties.RoomId.eq(roomId)).list();
        if(equips.size()>0)
            return true;
        return false;
    }

    public static void deleteAllTask() {
        daoSession.getTaskDao().deleteAll();
    }
} 
  

 

你可能感兴趣的:(greendao)