Android GreenDao数据库框架使用

本文详细介绍了如何使用GreenDao数据库框架在Android项目中进行数据库操作,包括创建项目、生成代码、在Android中使用以及封装常用数据库操作方法。通过实例代码展示插入、查询、更新和删除数据的操作,简化了传统SQLite数据库的复杂性,提供了更高效、便捷的数据管理解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android GreenDao数据库框架使用

初次使用的生活遇到很多问题,搞了好久才搞出来,写这篇文章只是为了记录下来遇到的问题,便于以后查询以及对初学者的一点提示吧。

  • 开始前的准备工作
  • 创建java项目
  • 下载需要的jar文件
  • 创建Android工程
  • 在Android项目中使用greendao

1、开始前需要到greendao官网下载相应的包文件

http://greendao-orm.com/documentation/how-to-get-started/这里是官方说明文档可以参考。
需要的三个jar分别是(版本最好要一致—都是最新的版本即可):
freemarker2.3.23.jar
http://sourceforge.net/projects/freemarker/files/freemarker/

greendao-generator-2.1.0.jar
http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22de.greenrobot%22%20AND%20a%3A%22greendao-generator%22

greendao2.1.0.jar
http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22de.greenrobot%22%20AND%20a%3A%22greendao%22

前两个jar包是放在java项目中使用的 greendao是在Android项目中使用

2、创建java项目JavaGreenDao,新建ExampleDaoGenerator类

public class ExampleDaoGenerator {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        // 参数3是数据库版本号,“com.cn.speedchat.greendao”是包名,也就是说生成的Dao文件会在这个包下,可以将Schema理解为数据库上下文吧
        Schema schema = new Schema(3, "com.allen.greendao");
        // addNote() addSession() addReplay()这三个函数相当于建立了三个表,表名你都可以不用管了会自动生成
        addNote(schema);
        // 这个是生成Dao文件的路径的位置,这个代表当前工程的上一级目录的JavaGreenDao的src文件夹里面
        new DaoGenerator().generateAll(schema, "../JavaGreenDao/src");

    }

    // 这个是一个Note表,然后后面的node.add***是表的字段名以及属性
    private static void addNote(Schema schema) {
        // "NoteEntity"相当于是表的类名,用NoteEntity生成对象就可以访问这个表属性了,也就是这个表对应了这个类,待会使用你就会明白了
        Entity note = schema.addEntity("NoteEntity");
        note.addIdProperty().autoincrement();
        note.addIntProperty("mode").notNull();
        note.addStringProperty("sessionid").notNull();
        note.addStringProperty("from").notNull();
        note.addStringProperty("to").notNull();
        note.addStringProperty("v_code");
        note.addStringProperty("timestamp").notNull();
        note.addStringProperty("platform");
        note.addStringProperty("message");
        note.addBooleanProperty("isread").notNull();
        note.addLongProperty("gossipid");
        note.addStringProperty("gossip");
        note.addIntProperty("chattype").notNull();
        note.addStringProperty("imagepath");
    }
}

运行java项目之后会在控制台打印如下消息则表示成功生成greendao需要在Android中使用的文件

This program comes with ABSOLUTELY NO WARRANTY
Processing schema version 3...
Written /Users/Allen/Documents/java/eclipse/workspace/JavaGreenDao/src/com/allen/greendao/NoteEntityDao.java
Written /Users/Allen/Documents/java/eclipse/workspace/JavaGreenDao/src/com/allen/greendao/NoteEntity.java
Written /Users/Allen/Documents/java/eclipse/workspace/JavaGreenDao/src/com/allen/greendao/DaoMaster.java
Written /Users/Allen/Documents/java/eclipse/workspace/JavaGreenDao/src/com/allen/greendao/DaoSession.java
Processed 1 entities in 204ms

如果出现以下错误说明是jar包版本不统一导致的,都到官网下载最新版本即可
这里写图片描述

成功生成代码之后F5刷新项目即可看到如图所示生成的文件,错误提示不要管,把这个包下的文件全部复制到Android项目中就没有错误了

这里写图片描述

3、在Android项目中使用greendao数据库

如下代码实现插入一个Note对象:

   DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        noteDao = daoSession.getNoteDao();
        Note note = new Note(null, noteText, comment, new Date());
        noteDao.insert(note);

代码变得如此简单。

官方推荐将取得DaoMaster对象的方法放到Application层这样避免多次创建生成Session对象

最好封装方法便于数据库的操作

public class GreenDaoUtils {
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private ChannelItemDao channelItemDao;
    private Context context;

    public GreenDaoUtils(Context context) {
        super();
        this.daoMaster = getDaoMaster(context);
        this.daoSession = getDaoSession(context);
        this.channelItemDao = daoSession.getChannelItemDao();
    }

    public DaoMaster getDaoMaster(Context context) {
        if (daoMaster == null) {
            OpenHelper helper = new DaoMaster.DevOpenHelper(context,
                    "database_name", null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    public DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    /**
     * 插入数据
     *
     * @param tname
     * @param tid
     * @param orderid
     * @param selected
     */
    public void insertGreenDao(String tname, String tid, int orderid,
                               int selected) {
        ChannelItem channelItem = new ChannelItem(null, tname, tid, orderid,
                selected);
        channelItemDao.insert(channelItem);
    }

    /**
     * 获取数据 根绝selected选取是否是用户选择的新闻频道
     *
     * @param selected 值是0/1
     * @return
     */
    public List<ChannelItem> getChannelItems(int selected) {
        QueryBuilder<ChannelItem> channelBuilder = channelItemDao
                .queryBuilder();
        channelBuilder.where(Properties.Selected.eq(selected));
        channelBuilder.orderAsc(Properties.Id);
        List<ChannelItem> channelItems = channelBuilder.list();
        return channelItems;
    }

    /**
     * 删除数据
     *
     * @param channelItem
     */
    public void deleteChannel(ChannelItem channelItem) {
        channelItemDao.delete(channelItem);
    }

    /**
     * 删除所有数据
     */
    public void deleteAllData() {
        channelItemDao.deleteAll();
    }

    /**
     * 保存用户频道到数据库
     *
     * @param userList
     */
    public void saveUserChannel(List<ChannelItem> userList) {
        for (int i = 0; i < userList.size(); i++) {
            insertGreenDao(userList.get(i).getName(), userList.get(i).getTid(), i, 1);
        }
    }

    /**
     * 保存其他频道到数据库
     *
     * @param otherList
     */
    public void saveOtherChannel(List<ChannelItem> otherList) {
        for (int i = 0; i < otherList.size(); i++) {
            insertGreenDao(otherList.get(i).getName(), otherList.get(i).getTid(), i+100, 0);
        }
    }
}

看到这里想必都已经理解的差不多了,那就赶紧实战中应用起来吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值