Android GreenDao使用详解

做Android开发总难免与数据库打交道的。但是原生的数据库操作总是那么的复杂且效率很低。所以决定使用第三方的数据库操作。目前有很多的第三方的数据库框架如Ormlite这是目前比较火的Orm数据库框架,且这种比较符合JavaEE开发者使用习惯,注解很方便。而GreenDao则为Android大大优化,使用最小的内存,非常高的性能优势。下面是网上的一个对比图:这里写图片描述
由此我们可以发现GreenDao的优势与效率,况且目前使用的非常广泛。所以以后决定就使用这种数据库了。下面我将一步一步的讲解如何使用这个很牛的数据库框架。

  • 首先你必须有一个生产DaoMaster,DaoMessina以及Dao和数据库表的java文件。所以我们建一个java工程然后在Gradle配置如下,我这里使用的是目前最新的故使用如下的配置:
compile 'de.greenrobot:greendao-generator:2.0.0'

然后我们就完成了java工程的配置。

  • 然后我们写一个Main函数用于生成我们的Java数据库相关的类如下:
public class StudentDaoGenerator {
    public static void main(String[] args) throws Exception {
    //第一个为数据库的版本号,第二个是自动生成数据库相关文件的包名
        Schema schema = new Schema(1, "cn.zzu.wgp.cardao");
        // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。
        addCars(schema);//这里就是我们创建一个表
        // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录这里我创建一个java-gen的文件夹。

        new DaoGenerator().generateAll(schema, "D:\\CodeSource\\AADemo\\app\\src\\main\\java-gen");
    }

    private static void addCars(Schema schema) {
        Entity cars = schema.addEntity("Cars");//指明表名
        cars.addLongProperty("carId").primaryKey().autoincrement();//设置字段
        cars.addStringProperty("hp").notNull();//向数据库中添加字段
        cars.addStringProperty("host").notNull();
        cars.addIntProperty("weizhang").notNull();
    }


}

这样我们就完成了数据的建立是不是很简单呀,至此我们还没有写一行sql语句是不是很简单呀!接下来我们到Android工程中。java工程的工作就算做完了。

  • 首先Android下的Gradle配置
    我们需要如下的gradle配置就可以了(注意Android和java的配置不一样的)
compile 'de.greenrobot:greendao:2.0.0'

加上这样的配置就可以了

  • 我们可以看到在Android工程中已经为我们生成了Cars,CarsDao,DaoMaste,DaoSession这四个java文件
  • Cars
public class Cars {

    private Long carId;
    /** Not-null value. */
    private String hp;
    /** Not-null value. */
    private String host;
    private int weizhang;

    public Cars() {
    }

    public Cars(Long carId) {
        this.carId = carId;
    }

    public Cars(Long carId, String hp, String host, int weizhang) {
        this.carId = carId;
        this.hp = hp;
        this.host = host;
        this.weizhang = weizhang;
    }

    public Long getCarId() {
        return carId;
    }

    public void setCarId(Long carId) {
        this.carId = carId;
    }

    /** Not-null value. */
    public String getHp() {
        return hp;
    }

    /** Not-null value; ensure this value is available before it is saved to the database. */
    public void setHp(String hp) {
        this.hp = hp;
    }

    /** Not-null value. */
    public String getHost() {
        return host;
    }

    /** Not-null value; ensure this value is available before it is saved to the database. */
    public void setHost(String host) {
        this.host = host;
    }

    public int getWeizhang() {
        return weizhang;
    }

    public void setWeizhang(int weizhang) {
        this.weizhang = weizhang;
    }

}

我们可以发现这里面就是一堆新的get和set方法这个就是数据库的表

  • 你或许很好奇我们如何不写sql语句就能建表呢,这里其实框架已将给我们做好了。就在CarDao中
    这里面就是创建表的文件,大家可以自己看一看我们这里就不在详细介绍了。

  • 下面就是两个非常总要的类DaoMaster和DaoMession从名称我们就可以发现他的重要性了这里我们一般不更改这里的代码我们需要写一个类管理这两个‘顶头上司’。

package cn.zzu.wgp.dao;


import android.content.Context;

import cn.zzu.wgp.cardao.DaoMaster;
import cn.zzu.wgp.cardao.DaoSession;

/**
 * Created by wanggp on 2015/12/17.
 */
public class CarGreenDao {
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    /**
     * 获取最高的数据库管理DaoMaster
     *
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context) {
        if (daoMaster == null) {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, "car_db1", null);//第二个参数为数据库的名称
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 获取daoSession实例
     *
     * @param context
     * @return
     */
    public static DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
}

接下来我们就用这个类来管理这两个上司了。
数据库吗总免不了增删改查这四个操作。所以这里我们编写一个接口来完成这部分工作。如下一个Dbservice

public interface CarDbService {
    /**
     * 添加一个车辆
     *
     * @param car
     * @return
     */
    public Cars insertCar(Cars car);

    /**
     * 删除一个车辆信息
     *
     * @param id
     */
    public void deleteCar(long id);

    /**
     * 通过id获得一个车辆
     *
     * @param id
     * @return
     */
    public Cars getCarById(long id);

    /**
     * 通过一个模糊查询获得一个车辆列表
     *
     * @param value
     * @return
     */
    public List<Cars> getCarsByLike(String value);

    /**
     * 通过名称查询车辆信息
     *
     * @param name
     * @return
     */
    public Cars getCarByName(String name);

    /**
     * 更新一个车辆信息
     *
     * @param car
     */
    public Cars updateCar(Cars car);

}

接下来我们在编写一个数据库的操作类就是我们常用的Dao类如下:

public class CarsService implements CarDbService {
    private DaoMaster daoMaster;//这里提醒一下这里的DaoMa一定是我们要操作数据库的DaoMaster如果你建了很多的表则这个很重要,我就是因为导错包纠结很久的。DaoSession一样的。
    private static DaoSession daoSession;
    private static CarsService service;
    private CarsDao carsDao;

    public CarsService(CarsDao carsDao) {
        this.carsDao = carsDao;
    }

    public static CarsDao getCarsDao11() {
        return daoSession.getCarsDao();
    }

    public static CarsService getService(Context context) {
        if (service == null) {//获取CarService的方法
            daoSession = CarGreenDao.getDaoSession(context);
            service = new CarsService(daoSession.getCarsDao());
        }
        return service;
    }

    /**
     * 添加一个车辆
     *
     * @param car
     * @return
     */
    @Override
    public Cars insertCar(Cars car) {
        return carsDao.loadByRowId(carsDao.insertOrReplace(car));//通过这个语句来向数据库中添加一个实例
    }

    /**
     * 删除一个车辆信息
     *
     * @param id
     */
    @Override
    public void deleteCar(long id) {

        carsDao.deleteByKey(id);//删除操作
    }

    /**
     * 通过id获得一个车辆
     *
     * @param id
     * @return
     */
    @Override
    public Cars getCarById(long id) {
        //通过id查询
        return carsDao.queryBuilder().where(CarsDao.Properties.CarId.eq(id)).unique();
    }

    /**
     * 通过一个模糊查询获得一个车辆列表
     *
     * @param value
     * @return
     */
    @Override
    public List<Cars> getCarsByLike(String value) {
        return carsDao.queryBuilder().where(CarsDao.Properties.Hp.like("%" + value + "%")).list();
    }

    /**
     * 通过名称查询车辆信息
     *
     * @param name
     * @return
     */
    @Override
    public Cars getCarByName(String name) {
        return carsDao.queryBuilder().where(CarsDao.Properties.Host.eq(name)).unique();
    }

    /**
     * 更新一个车辆信息
     *
     * @param car
     */
    @Override
    public Cars updateCar(Cars car) {
        carsDao.update(car);
        return car;
    }

    public CarsDao getCarsDao() {
        return carsDao;
    }

    public List<Cars> getAll() {
        return carsDao.loadAll();
    }

大家可以看到我们的增删改查是不是很简单呀,都不用谢sql语句几乎都是一行代码就搞定了。上面的查询只是简单的查询,大家如果感兴趣可以自己去查这些查询条件的,以后我还会介绍这种查询的。

  • 由于GreenDao官方建议我们将DaoMaster和DaoMession放在Application中就是全局变量。所以这里我们要在Application中如下的写:
public class BaseApplication extends Application {
    public IOrderHeaderService orderHeaderService;
    public CarsService carsService;

    @Override
    public void onCreate() {
        super.onCreate();
        orderHeaderService = OrderHeaderService
                .getService(getApplicationContext());
        carsService = CarsService.getService(getApplicationContext());//获得carsService对象
    }
}

好了准备工作都已经做完了,下面就该我们的Activity上场了。这里我们操作就很简单了。如下:

public class CarsActivity extends Activity {
    private TitleView titleView;
    private FlatButton flatButton, search;
    private SQLiteDatabase db;
    private EditText name, cph, wzs;
    private DaoMaster daoMaster;//导包时一定注意导入你要操作数据库的包
    private DaoSession daoSession;//同样注意导包
    private Cursor cursor;
    public static final String TAG = "DaoExample";
    private CarsService daoCarsService;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.cars);
        titleView = (TitleView) findViewById(R.id.studenttitle);
        flatButton = (FlatButton) findViewById(R.id.add);
        search = (FlatButton) findViewById(R.id.search);
        listView = (ListView) findViewById(R.id.listview1);
        name = (EditText) findViewById(R.id.name);
        cph = (EditText) findViewById(R.id.cph);
        wzs = (EditText) findViewById(R.id.wzs);
        titleView.setTitleText("我的项目数据库显示");
        daoCarsService = ((BaseApplication) getApplication()).carsService;//获得数据操作服务,拿到这个后我们就可以进行操作了。
        List<Cars> cars = daoCarsService.getAll();//这就是查询全部的语句就一行代码
        final List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
        for (Cars car : cars) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("Hp", car.getHp());
            map.put("Host", car.getHost());
            map.put("wz", car.getWeizhang() + "");
            data.add(map);
        }
        Log.d("222222", daoCarsService.getCarsDao().getTablename());
        Log.d("222222", daoCarsService.getCarsDao().getAllColumns().length + "");
//        cursor = db.query(getStudentDao().getTablename(), getStudentDao().getAllColumns(), null, null, null, null, orderBy);
//        cursor = db.query("CARS", new String[]{"Hp", "Host"}, null, null, null, null, null);

//        String[] from = {"Hp", "Host", "wz"};
//        int[] to = {R.id.hp, R.id.host, R.id.wz};
        SimpleAdapter adapter = new SimpleAdapter(CarsActivity.this, data, R.layout.listviewitem, new String[]{"Hp", "Host", "wz"}, new int[]{R.id.hp, R.id.host, R.id.wz});
        listView.setAdapter(adapter);
        flatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name1 = name.getText().toString().trim();
                String cphm = cph.getText().toString().trim();
                int wzss = Integer.parseInt(wzs.getText().toString().trim());
                Cars car1 = new Cars(null, cphm, name1, wzss);
                daoCarsService.insertCar(car1);//向数据库中添加一个实例,也是一行代码
                List<Cars> cars = daoCarsService.getAll();
                final List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
                for (Cars car : cars) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("Hp", car.getHp());
                    map.put("Host", car.getHost());
                    map.put("wz", car.getWeizhang() + "");
                    data.add(map);
                }

                SimpleAdapter adapter = new SimpleAdapter(CarsActivity.this, data, R.layout.listviewitem, new String[]{"Hp", "Host", "wz"}, new int[]{R.id.hp, R.id.host, R.id.wz});
                listView.setAdapter(adapter);
//                Log.d("------", "添加成功了!" + car.getHost() + "---" + car.getHp() + "---" + car.getWeizhang());
            }
        });
    }

}

是不是很简单呀这样我们就完成了数据的简单操作,同样你可以根据自己的需求进行相应的改变与调整。以后我可能会po上关于这方面的一些操作。上面我做了一些实验的数据。主要用一个ListView和SimpleAdapter大家感兴趣的话可以查看如下的布局:
listviewitem,这个基本条目的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/hp"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/host"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/wz"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        />
</LinearLayout>  

cars.xml主布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#fff"
    android:orientation="vertical">

    <cn.zzu.wgp.view.TitleView
        android:id="@+id/studenttitle"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"

            android:text="姓名" />

        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="4"
            android:background="@null" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="车牌号" />

        <EditText
            android:id="@+id/cph"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="4"
            android:background="@null" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="违章数" />

        <EditText
            android:id="@+id/wzs"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="4"
            android:background="@null" />
    </LinearLayout>

    <cn.zzu.wgp.view.FlatButton
        android:id="@+id/add"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="增加" />

    <cn.zzu.wgp.view.FlatButton
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="查询" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="ID" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="姓名" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="违章数" />
    </LinearLayout>

    <ListView
        android:id="@+id/listview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"></ListView>
</LinearLayout>

这里面有很多我自己写的控件你不能自己拿来用,可供大家参考的。好了关于GreenDao这个框架就先介绍到这里。

PS:这个框架的数据库升级是删除所有的表的,就是你以前的数据会全部丢失的。你们也许会好奇万一面临数据升级该如何办呢。这个其实很简单的。我将在以后的博文中会介绍如何处理的。尽请大家持续关注!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值