转:http://blog.surecase.eu/using-greendao-with-android-studio-ide/

In this tutorial we will show you step by step how we have created sample application that presents our own Android Studio-GreenDao communication module. We tried to focus mainly on the implementation of database in freshly created Android Studio project and took other factors (such as layouts, modularity etc.) with a grain of salt. For those who haven't checked our Git yet - you can find our GreenDao module here.

So let's get started!

Step 1 - create new Android Project

For those who are not familiar with Android Studio IDE we recommend to go through Google tutorial - Getting Started With Android Studio.

  1. To create new project please select File -> New Project. The New Project wizards pop up. Fill up fields according to your liking or do it the way we did: 

    1. Press next. Check "Blank Activity" and next button again.
    2. Name your first activity BoxListActivity and the layout activity_box_list.
    3. Press finish.

And it's done. We have our project created. Now we can go to next step which is...

Step 2 - add GreenDao Generator module to project tree

We assume you have already downloaded our module. If not please go to our Git and do it now. Add MyDaoGenerator module to your project tree as additional package.

As you can see MyDaoGenerator is recognized as Directory and not as Module like DaoExample. To change it we have to edit settings.gradle so it contains both ':DaoExample' and ':MyDaoGenerator' :

include ':DaoExample', ':MyDaoGenerator'

After doing it, please click "Sync Project with Gradle Files" button. Your directory should look like a module now in project tree.

Step 3 - connect GreenDao Generator to DaoExample (main module)

So, MyDaoGenerator is currently recognized as a module. Now we have to configure it, so we can get database files from it. The only necessary thing to be changed is outputDir parameter inbuild.gradle file of MyDaoGenerator module.

12345678910111213141516171819202122
project(':MyDaoGenerator') {
apply plugin: 'application'
apply plugin: 'java'
 
mainClassName = "pl.surecase.eu.MyDaoGenerator"
// edit output direction
outputDir =
 
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('de.greenrobot:DaoGenerator:1.3.0')
}
 
task createDocs {
def docs = file(outputDir)
docs.mkdirs()
}
 
run {
args outputDir
}
}

Currently our root is MyDaoGenerator. We want to access DaoExample, which needs database files. To go higher - our path will start with:

outputDir = "../"

We are currently in GreenDaoForAndroidStudio folder. We can easly go into DaoExample and create a directory for our database files. Java files in Android Studio project are stored in ../<PROJECT NAME>/src/main/java directory. To highlight the fact, that GreenDao database files are generated and will change in future as your project develops, we decided to create separate directory for them named java-gen.

Finaly our path looks like:

outputDir = "../DaoExample/src/main/java-gen"

There is no need to create this directory manualy. After running MyDaoGenerator it will be created during build.

Your GreenDao generator is now ready to inject database files to your project.

Step 4 - configure GreenDao Generator

MyDaoGenerator consists of only one class:

Output of GreenDao Generator is deremined by content of MyDaoGenerator.class. You can create your database structure here by coding objects, relations etc. If you are not familiar with GreenDao database library, you can learn how to use it in that documentation.

We will create exemplary database with only one object. Database code needs to be placed in main method:

public class MyDaoGenerator {

    public static void main(String args[]) throws Exception {
}
}

Create Schema object with represents database version and package. We will name the package greendao.

Schema schema = new Schema(3, "greendao");

We create Entity - database object which will be named Box.

Entity box = schema.addEntity("Box");

Now we can add properties/fields to our database Entity/Object. For example:

  • id
box.addIdProperty();
  • String name
box.addStringProperty("name");
  • int slots
box.addIntProperty("slots");
  • String description
box.addStringProperty("description");

Finaly we can invoke DaoGenerator object which is avaliable by default in MyDaoGenerator due to Maven tool (check gradle.build and dependencies section). DaoGenerator during run will create database java files that can be used in our main project. It takes two parameters: Schema and output directory.

new DaoGenerator().generateAll(schema, args[0]);

When you look at gradle.build there is a run section in which outputDir parameter is being sent to main method as an argument. That's why args[0] will always contain output path that you have set previously in gradle. Such operation limits actions performed on MyDaoGenerator to only three steps:

  • set path in gradle.build file
  • create your database in MyDaoGenerator.class
  • run module

Step 5 - run GreenDao Generator

Pick Gradle bookmark from the right side of Android Studio interface. Choose MyDaoGenerator module and click twice on run task.

greenDAO Generator
Copyright 2011-2013 Markus Junginger, greenrobot.de. Licensed under GPL V3.
This program comes with ABSOLUTELY NO WARRANTY
Processing schema version 3...
Written /Users/surecase/dev/examples/GreenDaoForAndroidStudio/GreenDaoForAndroidStudio/DaoExample/src/main/java-gen/greendao/BoxDao.java
Written /Users/surecase/dev/examples/GreenDaoForAndroidStudio/GreenDaoForAndroidStudio/DaoExample/src/main/java-gen/greendao/Box.java
Written /Users/surecase/dev/examples/GreenDaoForAndroidStudio/GreenDaoForAndroidStudio/DaoExample/src/main/java-gen/greendao/DaoMaster.java
Written /Users/surecase/dev/examples/GreenDaoForAndroidStudio/GreenDaoForAndroidStudio/DaoExample/src/main/java-gen/greendao/DaoSession.java
Processed 1 entities in 103ms BUILD SUCCESSFUL Total time: 8.802 secs

After starting run task, you can track flow of this operation in Gradle console. When it's complete you can see new files in DaoExample project:

And that's all work connected to MyDaoGenerator. If you are familiar with it, generation of new database will take only few minutes.

Step 6 - make DaoExample aware of new files

So we have successfully created database files that are ready to be used in any Android project. The project needs to be aware where are those files located and familiar with GreenDao objects. To achieve this it is necessary to configure build.gradle file of DaoExample module. Fresh build.gradle file of a new project looks similar to this:

123456789101112131415161718192021222324
apply plugin: 'android'
 
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
 
defaultConfig {
minSdkVersion 11
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
 
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
  • We need to clean it first from features that we won't use in our project - buildTypes section is not needed.
  • To let our project use GreenDao database, first we need to import GreenDao library. We can do it by inserting *.jar file into libs folder or by adding extra Maven dependency in gradle:
 dependencies {
compile 'de.greenrobot:greendao:1.3.7'
}
  • Project is still not aware of new Java files because it isn't located in ../<PROJECT NAME>/src/main/java directory. To fix this we must specify projects source sets. It is important to point two java file sources: /src/main/java and /src/main/java-gen. You can do it by placingsourceSets section into android section in gradle.build file:
12345678910
android {
 
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java', 'src/main/java-gen']
res.srcDirs = ['src/main/res']
}
}
}
view rawsourceSets.groovy hosted with ❤ by GitHub

Finaly our gradle will look like this:

12345678910111213141516171819202122232425262728
apply plugin: 'android'
 
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
 
defaultConfig {
minSdkVersion 11
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
 
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java', 'src/main/java-gen']
res.srcDirs = ['src/main/res']
}
}
 
}
 
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'de.greenrobot:greendao:1.3.7'
}
view raweditedGradle.groovy hosted with ❤ by GitHub

When you finish editing gradle file, press "Sync Project with Gradle Files" button. Your java-gen directory will look the same as java folder in project tree.

Step 7 - start Database

Your project is ready to use previously created database. To have access to GreenDao database, you have to initialize it before using it. Right place for performing this operation is Application class which is instantiated for you when the process for your application/package is created. Initialization code can be found on GreenDao webpage. Application is avaliable from every activity, so we create DaoSession object which is avaliable during whole lifecycle of application and create getter for it.

12345678910111213141516171819202122
public class DaoExampleApplication extends Application {
 
public DaoSession daoSession;
 
@Override
public void onCreate() {
super.onCreate();
setupDatabase();
}
 
private void setupDatabase() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "example-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
 
public DaoSession getDaoSession() {
return daoSession;
}
 
}

Don't forget to register DaoExampleApplication class in your manifest:

<application
android:name=".DaoExampleApplication"
(...)
</application>

Step 8 - simple operations on DB object

Database generated in this tutorial has only one Entity - Box. To perform create, edit, save, delete on it, we need too create helper class with those methods. We name it BoxRepository. Each Entity created in GreenDao has two classes:

  • class that represents structure of object
  • Dao class which is a connection of object with database

In our example those clasess are named as Box and BoxDao. So if we want start working with Box objects we need to get BoxDao object from DaoSession that was created with Application class.

private static BoxDao getBoxDao(Context c) {
return ((DaoExampleApplication) c.getApplicationContext()).getDaoSession().getBoxDao();
}

With access to DaoBox we can perform any operation on Box object we need. Examplary BoxRepository from our project looks like this:

1234567891011121314151617181920212223242526
public class BoxRepository {
 
public static void insertOrUpdate(Context context, Box box) {
getBoxDao(context).insertOrReplace(box);
}
 
public static void clearBoxes(Context context) {
getBoxDao(context).deleteAll();
}
 
public static void deleteBoxWithId(Context context, long id) {
getBoxDao(context).delete(getBoxForId(context, id));
}
 
public static List<Box> getAllBoxes(Context context) {
return getBoxDao(context).loadAll();
}
 
public static Box getBoxForId(Context context, long id) {
return getBoxDao(context).load(id);
}
 
private static BoxDao getBoxDao(Context c) {
return ((DaoExampleApplication) c.getApplicationContext()).getDaoSession().getBoxDao();
}
}
view rawboxRepository.java hosted with ❤ by GitHub

Examplary use that can be used in every place where Context is avaliable:

Box box = new Box();
box.setId(5); // if box with id 5 already exists in DB, it will be edited instead of created
box.setName("My box");
box.setSlots(39);
box.setDescription("This is my box. I can put in it anything I wish.");
BoxRepository.insertOrUpdate(context, box);

Step 9 - rest is up to you

This is the end of this tutorial. You have all information and tools you need to start work with GreenDao database in your Android Studio project. There is no need to show you how to create views, buttons, adapters etc. If you are interested in it - whole source code and project structure of GreenDaoForAndroidStudio sample project is avaliable at SureCase git.

Android GreenDao with Android Studio IDE的更多相关文章

  1. [转] - Configuring Android Studio: IDE & VM Options, JDK, etc

    Configuring Android Studio: IDE & VM Options, JDK, etc You should not edit any files in the IDE ...

  2. Android Studio IDE 插件开发

    作者:字节跳动终端技术--周宸韬 概述 这篇文章旨在向读者介绍IntelliJ IDE插件的开发流程以及常用的一些通用功能,任何基于IntelliJ开发的IDE都可以通过该方式制作插件,例如Andro ...

  3. android studio IDE 下,设置ACTIVITY全屏

    因为ANDROID STUDIO的JAVA类是继承AppCompatActivity的 ,所以常规的全屏设置并不管用.如果要设置全屏,请参照如下代码/ 1/首先,打开AndroidManifest.x ...

  4. how to use greendao in android studio

    http://www.arjunsk.com/android/use-greendao-android-studio/ 1.新建一个java文件MainGenerator.java: import d ...

  5. [Android] Android GreenDao 保存 JavaBean 或者List <JavaBean>类型数据

    Android GreenDao 保存 JavaBean 或者List <JavaBean>类型数据 简介 数据库存储数据基本上每个APP都有用到,GreenDAO 是一个将对象映射到 S ...

  6. Android开发工具Android Studio、Android SDK和Genymotion完全配置

    所谓“工欲善其事,必先利其器”.Android Studio 是谷歌推出一个Android集成开发工具,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提 ...

  7. 【Mac + Android】之Android Studio 环境搭建,AVD模拟器运行(包括:命令行运行AVD,并且Genymotion模拟器插件配置运行)

    目录: 前提.Mac环境下手动配置Android SDK 一. Android Studio下载及配置 二.AVD模拟器配置运行 扩展:命令行运行AVD模拟器 三.在Android Studio 中配 ...

  8. 《Android Studio实战 快速、高效地构建Android应用》--Android Studio操作

    前言 摩尔定律:CPU的处理能力大约18个月翻一倍 Android&Java:想要在Android Studio中开发Android App,必须以充分了解Java为前提(Java流行的原因: ...

  9. Android精通教程-Android入门简介

    前言 大家好,我是 Vic,今天给大家带来Android精通教程-Android入门简介的概述,希望你们喜欢 每日一句 If life were predictable it would cease ...

随机推荐

  1. Linux系统的简介及Linux系统的安装

    一.写在前面  本文仅仅对Linux系统进行简要的概述已经对Linux系统的安装进行简要的介绍 二.完成目标 1.Linux操作系统的基本概念 2.Linux系统的安装 三.基本概念 1.什么是操作系 ...

  2. AES 加密,C#后台,javascript前台,crypt-js

    javascript前台代码 <script src="http://apps.bdimg.com/libs/crypto-js/3.1.2/components/core-min.j ...

  3. Android 四大组件之Activity生命周期

    写这篇博文之前,已经对android有一定的了解和认识.这篇博文主要讲述android的Activity的生命周期,这是android开发者必须掌握的知识.android的Activity组件拥有7个 ...

  4. web中通过注释判断浏览器<!--[if !IE]><!--[if IE]><!--[if lt IE 6]><!--[if gte IE 6]>版本

    <!--[if !IE]><!--> 除IE外都可识别 <!--<![endif]--><!--[if IE]> 所有的IE可识别 <![e ...

  5. sql语句批量处理Batch

    package Statement批量处理; import java.sql.Connection; import java.sql.DriverManager; import java.sql.St ...

  6. 动态获取UIWebView的真正高度

    场景 在 App 中使用UIWebView加载网页, 与原生的 UI 显示在一起,一般情况下,webView 的 内容一页是肯定不够的,换句话说,webView 的高度是不定的,那如果原生的 UI是一 ...

  7. Linux下如何查看哪些进程占用的CPU内存资源最多

    linux下获取占用CPU资源最多的10个进程,可以使用如下命令组合: ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head linux下获取占用 ...

  8. SpringMVC(二) —— 中文乱码处理

    Get的乱码处理 改tomcat中server.xml中的port=“8080”,加上一个 URIEncoding=”utf-8” 如下图: 2.Post乱码的处理 在web.xml文件中加入 < ...

  9. java synchronized使用

    java synchronized 基本上,所有并发的模式在解决线程冲突问题的时候,都是采用序列化共享资源的方案.这意味着在给定时刻只允许一个任务访问该资源.这个一般通过在代码上加一条锁语句实现,因为 ...

  10. C++中的操作符重载

    一.什么是操作符重载 操作符重载可以分为两部分:“操作符”和“重载”.说到重载想必都不陌生了吧,这是一种编译时多态,重载实际上可以分为函数重载和操作符重载.运算符重载和函数重载的不同之处在于操作符重载 ...