03 Nov 2015

Some project-structure advices(Android Studio)

Hello!

Here are some brief advices concerning project structure(gradle based) in Android Studio

The structure is pretty simple, it's gonna save you a lot of time, and will make development process comfortable.

Add following lines to your build.gradle file in app module

buildTypes {
        debug{
            debuggable true
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        mock {
            applicationId = "com.your.application.id.mock"
            resValue "string", "app_name", "Your_app_name(D)"
        }
        production {
            applicationId = "com.your.application.id.production"
            resValue "string", "app_name", "Your_app_name"
        }
    }

Store your files in java folder following way:

smth went wrong

So it will give you different configuration of the project. You can switch them in Build Variants windows on Android Studio.

So you can have different implementation for certain classes in your project. For example you can create mock server implementation to test the project even if the server is down or not ready at the moment

Note that if you want some classes to have different implementation in different build variants, just add this class to different configurations, but exclude this class from main. You can do it also with everything: resources,assets and so on

Also some staff about signing your apk-file. A lot of people use the wrong approach and store singing config information to their build.gradle file this way:

signingConfigs {
        debug {
            storeFile file(/somepath/...)
            storePassword 'android'
            keyAlias 'android'
            keyPassword 'android'
        }
            storeFile file(/somepath/...)
            storePassword 'android'
            keyAlias 'android'
            keyPassword 'android'
        }
    }

This approach is wrong because when you push your project to some public repo, the singing config data would be seen by all who have access to this public repo

There is a way how to resolve this problem:

In your root path of the project create new text-file "keystore.properties" with following content

storePassword=android
keyPassword=android
keyAlias=android
storeFile=../distribution/keystore

Then modify your build.gradle file

add it after apply plugin 'com.android.application'

def keystorePropertiesFile = rootProject.file("keystore.properties");
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

Then:

signingConfigs {
        debug {
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
        }
        release {
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
        }
    }

    buildTypes {
        debug{
            debuggable true
            signingConfig signingConfigs.debug
        }
        release {
            signingConfig signingConfigs.release
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

Here I showed some tips concerning project-structure. Next time i want to post something about Dagger 2

Good luck!

View Comments
15 Jul 2015

GreenDao ORM in Android Studio Part 2

Hello!

As I promised in part 1 I will show how to use greendao in your project. I will give some examples of One-To-One and One-To-Many relations

Here is GreenDaoGeneratorM class from greendao module as i showed in part1, fill it with following data

The data structure is pretty simple.

public class GreenDaoGeneratorM {
    public static void main(String args[]) throws Exception {
        generateTaskEntities();
    }

    private static void generateTaskEntities(){
        Schema schema = new Schema(1, "com.somepackage.somepackage.android.dbmodel");

        Entity introWindow=schema.addEntity("IntroWindow");
        introWindow.addIdProperty();
        introWindow.addStringProperty("name");
       

        Entity card = schema.addEntity("Card");
        card.addIdProperty();
        card.addStringProperty("name");
        card.addStringProperty("description");
         

        Entity taskSheet = schema.addEntity("TaskSheet");
        taskSheet.addIdProperty();
        taskSheet.addStringProperty("name");
        taskSheet.addStringProperty("description");
        
        //Creating One-To-One relation, TaskSheet has "one" introWindow
        Property introWindowIdProperty = taskSheet.addLongProperty("introWindowId").getProperty();
        taskSheet.addToOne(introWindow, introWindowIdProperty);

        
        //Creating One-To-Mane relation, TaskSheet has "many" cards
        Property taskSheetIdCard = card.addLongProperty("taskSheetId").notNull().getProperty();
        ToMany taskSheetToCards = taskSheet.addToMany(card, taskSheetIdCard);
        taskSheetToCards.setName("cards"); // Optional

        try {
            new DaoGenerator().generateAll(schema, "../main/src/java");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The TaskSheet instance has one IntroWindow and many Card instances

Just go to Gradle panel and make "run" command and generator will generate the Dao for you (see part1)

Now it's time to use it in the project

DataBaseExample.java

public class DataBaseExample{
	 public void initDatabase(){

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "task-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();

         TaskSheet taskSheetDb = new TaskSheet();
		 taskSheetDb.setName("some name");

		 IntroWindow introWindow = new IntroWindow();
		 introWindow.setName("intro");

		 IntroWindowDao introDao=daoSession.getIntroWindowDao();
		 introDao.insert(introWindow);
		 //method intro Window was generated automatically, id is generated by greendao, but you can also set it by yourself using setId() method
		 taskSheetDb.setIntroWindow(introWindow);
		 taskSheetDd.setIntroWindowId(introWindow.getId());

		  TaskSheetDao taskSheetDao = daoSession.getTaskSheetDao();
          taskSheetDao.insertOrReplace(taskSheetDb);
          
          Card card1=new Card();
          card1.setName("card1");
          //generated method
          card1.setTaskSheetId(taskSheetDb.getId());

          Card card2=new Card();
          card2.setName("card2");
          //generated method
          card2.setTaskSheetId(taskSheetDb.getId());

          CardDao cardDao = daoSession.getCardDao();
          cardDao.insertOrReplace(card1);
          cardDao.insertOrReplace(card2);
    }
    public void checkData(){
    	TaskSheetDao taskSheetDao= daoSession.getTaskSheetDao();
        List taskList = taskSheet.loadAll();
        List cards=taskList.get(0).getCards();
        IntroWindow introwindow=taskList.get(0).getIntroWindow();	
    }
    public void removeAllData(DaoSession daoSession){
        daoSession.getCardDao().deleteAll();
        daoSession.getTaskSheetDao().deleteAll();
    }
}

P.S. maybe you will find some mistakes in code, because it was modified in notepad, but still the most important thing is the logic of how it works

Here i showed simple usage of greendao. There are a lot of other important staff, but all of it you can find in documentation of greendao.

Good luck!

View Comments
30 Jun 2015

GreenDao ORM in Android Studio Part1

Hello!

Every android developer knows that boilerplate you are facing while working with SQLite Database. A lot of code that is repeated so often.

To avoid this boilerplate you can use different ORM. I'm going to show how to use greendao. But also below I will give brief description of the best 5 ORMs.

OrmLite

It's not android but java ORM. If you got used to annotations probably you would like it.

SugarORM

This ORM was created for Android. It's has easy to use and memorizable API and other sweet features

ActiveAndroid

This ORM is doing the same things as the other ones, also it has different annotations that make code more beautiful

Realm

It's written on C++ and has great performance

GreenDao

If you need great performance you should definitely look on GreenDao. It's working in 3.5-4 times faster than ORMLite

Using GreenDao in Android Studio

Adding dependencies

You are going to need 3 jars that you can get here:

freemaker

greendao

greendao generator

Or you can just use gradleplease from my former post

And add dependencies to gradle without downloading any jars

Note: there are some issues with freemaker if you are using maven-central dependencies.

Adding greendao generator to your project

GreenDao generator is wrapping your database, creating data model. It generates classes that you usually write by yourself. Generator is doing this annoying work for you.

By the way, generated classes look nice and are easily editable. So if you want some specific additional functionality you are free to edit them.

First, create new module on your project

smth went wrong

Then select Java Library

smth went wrong

smth went wrong

Modify build.gradle in your module following way:

apply plugin: 'application'
apply plugin: 'java'

mainClassName = "com.somepackage.greendao.GreenDaoGeneratorM"
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/greendao-generator-1.3.1.jar')
    compile files('libs/freemarker-2.3.22.jar')
}

Creating the data model

Open the class GreenDaoGeneratorM and add following:

public static void main(String args[]) throws Exception {
        Schema schema = new Schema(1, "com.guthub.jackwarthongithub.dbmodel");
    }

Then fill the main method with following content:

        Schema schema = new Schema(1, "com.guthub.jackwarthongithub.dbmodel");

        Entity person = schema.addEntity("Person");
        person.addIdProperty();
        person.addStringProperty("name");
        person.addStringProperty("comment");

        Entity lease = schema.addEntity("Lease");
        lease.addIdProperty();
        lease.addStringProperty("item");
        lease.addStringProperty("comment");
        lease.addLongProperty("leasedate");
        lease.addLongProperty("returndate");

        Property personId = lease.addLongProperty("personId").getProperty();
        lease.addToOne(person, personId);

        ToMany personToLease = person.addToMany(lease, personId);
        personToLease.setName("leases");

        new DaoGenerator().generateAll(schema, "../app/src/main/java");

As you can see, you are able to create relations without any sql code

To actually generate the model make "run" command in gradle on the right side of Android Studio

smth went wrong

That's it. Now if everything is fine. The generated classes will be created in package "dbmodel"

smth went wrong

smth went wrong

Using greendao is simple. You can find different information in official documetation

Next post I will show how to use greendao on some real example. I promise to show you OneToMany and OneToOne relations

View Comments
12 Jun 2015

Gradle Please

Hello!

Every android developer faced the problem when you are adding some dependency to your build.gradle or maven file and sometimes you can't find latest version of some library and this dependency can't be resolved.

dependencies {   
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.google.android.gms:play-services:7.5.0'
    compile 'io.segment.analytics.android:flurry:1.3.1'
    compile 'com.j256.ormlite:ormlite-android:4.48'
    compile 'com.j256.ormlite:ormlite-core:4.48'
    //compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
    compile 'com.googlecode.json-simple:json-simple:1.1.1'
    compile 'org.mozilla:rhino:1.7.6'
    compile 'junit:junit:4.12'
}  

I have good news for those who struggled with it!

Here is great website

Now it will be easy to add dependencies to your project

P.S. But still it's better to read library documentation and use the recommended version of the lib

View Comments

Older Posts

My First Post 12 Jun 2015 Comments