转: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 modulehere.

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 activityBoxListActivityand the layoutactivity_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 toour Gitand 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 editsettings.gradleso 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 isoutputDirparameter inbuild.gradlefile 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 } }
view raw MyDaoGeneratorgrad.groovyhosted with ❤ by GitHub

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/javadirectory. 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 namedjava-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 ofMyDaoGenerator.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 thatdocumentation.

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

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

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

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

We create Entity - database object which will be namedBox.

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

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

  • id
box.addIdProperty();  
  • Stringname
box.addStringProperty("name"); 
  • intslots
box.addIntProperty("slots"); 
  • Stringdescription
box.addStringProperty("description"); 

Finaly we can invoke DaoGenerator object which is avaliable by default in MyDaoGenerator due to Maven tool (checkgradle.buildanddependenciessection). 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 atgradle.buildthere is arunsection in whichoutputDirparameter is being sent to main method as an argument. That's whyargs[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 ingradle.buildfile
  • create your database inMyDaoGenerator.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 onruntask.

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 startingruntask, 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 configurebuild.gradlefile of DaoExample module. Freshbuild.gradlefile 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']) }
view raw defaultGradle.groovyhosted with ❤ by GitHub
  • 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 byinserting *.jar fileintolibsfolder 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/javadirectory. To fix this we must specify projects source sets. It is important to point two java file sources:/src/main/javaand/src/main/java-gen. You can do it by placingsourceSetssection intoandroidsection ingradle.buildfile:
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 raw sourceSets.groovyhosted 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 raw editedGradle.groovyhosted with ❤ by GitHub

When you finish editing gradle file, press "Sync Project with Gradle Files" button. Yourjava-gendirectory will look the same asjavafolder 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 onGreenDao 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; } }
view raw DaoExampleApplicaiton.javahosted with ❤ by GitHub

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 asBoxandBoxDao. So if we want start working with Box objects we need to getBoxDaoobject fromDaoSessionthat 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 onBoxobject 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 raw boxRepository.javahosted 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 atSureCase git.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. vue结合android,mint中popup和picker实现
  2. Android版本更新(断点下载)
  3. 探究J2ME和Android的几大区别
  4. android微信朋友圈分享
  5. android进程重启及activity恢复
  6. Android Edittext设置android:imeOptions
  7. 性能优化——Android图片压缩与优化的几
  8. Android探索之旅 | 面向对象和Java基础
  9. Android4.0 input touch解析
  10. Android从服务端获取json解析显示在客户