5 notes on MVP architecture pattern for Android

                                                           Image credits Macoscope

MVP (Model View and Presenter) is an architectural pattern inspired by the popular MVC pattern.

MVP addresses two main points :

  1. Make views as dumb as possible. The dumber the better.
  2. Make each layer loosely coupled and easily testable in isolation.

I am using MVP in one of my production project and have used in some dem0 apps. Here are my 5 notes on using MVP for android.

  1. Package Structure :

Android project contains lots of code and files even for application of medium complexity. Even when not following MVP I have found that arranging the project files in such a way that files that are accessed together are put in same package is more efficient and intuitive than any other approach.

What I prefer doing is create separate package for separate verticals of the app and put all related files like activities, fragments, views, presenters, adapters etc in that package.

ex. packages like add task, view task, list task for a To-Do app.

2. Libraries that are useful for MVP :

In MVP you want your model and presenter to be independent of the life cycle of view. For this, you can use dependency injector library like Dagger2.

Other than that, using RxJava and reactive programming principles for creating presenter is also becoming increasingly popular.

Libraries you can use for this purpose are : RxAndroid and EventBus.

3. Managing Remote and local data sources in the Model :

Android apps have to fetch data from the server. At the same time fetched data must be cached to make the app usable offline and increase the speed.

What I prefer doing is to create three model classes :

1. Remote Data Source

2. Local Data Source

3. Data Repository

All presenters talk to Data Repository class. Data repository model contains references to Local and Remote data repository and calls data from either according to situation.

As the name suggests Local Data Source deals with cached data and disk storage whereas Remote Data Source deals with API calls and responses.

4. User Experience is the top priority :

One thing that we all have to keep in mind that the real test of application is, if it is able to provide user a nice experience.

At the end of the day, user only notices the user experience of the application and not the architecture used. So if you have to make some design sacrifices to make the UX better, do it.

The real test of the machine is the satisfaction it provides to the mind. There is no other bigger test.

5. Testing Advantages :

Main motive behind MVP pattern was to make the testing of layers easy.

Basic idea is to keep the presenter and model android free, so that they can be tested without Android instrumentation by the JVM itself.

Views can then be tested by Android Instrumentation tests.

Mockito and Espresso can come handy for testing purposes.

Conclusion :

MVP, in my opinion is so far the best way to architect your android application project. It simplifies many issues like testing and making views lighter. Combine it it RxJava and dependency injection and you’ve got a nice recipe for android projects.

I am learning more about RxJava and testing frameworks will share my views on that soon.


Rails Number Helper Port to Android

A polyglot developer will understand, there is always something you like about one language and you wish was available for another language too.

So, recently I started learning rails and found number_helper API very cool and fun to use. It gives you easy API to convert numbers into many formats like number_to_human which will convert 20000 to 20 Thousands or number_to_human_size that will convert 1024 to 1 KB.

That was it I wanted this stuff for Android too. It just makes processing numbers to fit the UI needs so damn easy.

Here is my attempt to port this rails module to Android.

Here is the source code :


Usage : 

Just copy the module number_helper in your application folder and include module dependency.

Examples : 


        // Number to human converter
        NumberToHumanConverterBuilder builder2 = new NumberToHumanConverterBuilder(123456);
        NumberToHumanConverter converter2 = builder2.build();
        try {
            String humanNumber = converter2.convert();
            // OUTPUT : 123.456 Thousands
            Log.d(Config.TAG, humanNumber);
        } catch (InvalidSeparatorException | InvalidDelimiterException
                | InvalidPrecisionException e) {

Examples can be found here.

Features : 

  • Easy to use API.
  • High utility for UI needs.
  • Small in size.
  • Custom exceptions to fit the needs of Android.


Paint App in Android

Recently I was learning about Canvas and Custom views in Android and to put the theory in practice I made a pretty simple Paint App. 

Source code of the app can be found https://github.com/priyankvex/Paint-App-Android.

Screenshot of the app
Screenshot of the app


The App is pretty simple with features
1.  Create Drawings (Obvious one :P).
2.  Select different brush sizes.
3.  Eraser with different sizes.
4.  Color pallet.
5.  Save drawings in Gallery.

Source code of the app can be found https://github.com/priyankvex/Paint-App-Android.

Brownie points if you can guess the character I drew! 😀

Making an OCR app for Android using Tesseract.

Star on GitHub

Recently I was playing with OCR library by google called as “Tesseract” (cool name for a library!).

App in action.
App in action.











It was a fun experience. This post shows how you can make a simple OCR app in Android using Tesseract.

We will be using Tess-Two a fork of Tesseract with some additional tools like Liptonica which is an image processing library.

If you want an even easier way to get started with OCR on Android you can try this library built by me. Easy OCR Library. Usage instructions are in the ReadMe.md file there.

Anyways, moving forward I am using Android Studio on Ubuntu 64 bit machine here.

Step 1 : 

Clone the library Tess-Two.

git clone git://github.com/rmtheis/tess-two tess

Step 2 :

Now we need to build  the library.

For building we will need Android NDK.

cd tess
cd tess-two
android update project --path .
ant release

Building may take some time so be patient. Don’t press ctrl+c too soon 😛 .

Step 3  :

Yay! Time to use the library in Android Project.

Copy the tess/tess-two folder into the root folder of your application project.

Step 4 : 

In the tess-two folder you just pasted. Add build.gradle file as Android Studio uses gradle build system.

Add following gradle script in the file.

buildscript {
    repositories {
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

apply plugin: 'android-library'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 22

    sourceSets.main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        res.srcDirs = ['res']
        jniLibs.srcDirs = ['libs']

Step 5 : 

Add the following line in project.settings file.

include ':tess-two'

Step 6 :

Now we have successfully included the Tess-Two library in our project and we are ready to use it.

First we need to capture the picture itself. You can use something like this code sample taken from Easy OCR Library.

public void takePicture(){
        Intent e = new Intent("android.media.action.IMAGE_CAPTURE");
        this.filePathOriginal = FileUtils.getDirectory(this.directoryPathOriginal) + File.separator + Calendar.getInstance().getTimeInMillis() + ".jpg";
        e.putExtra("output", Uri.fromFile(new File(this.filePathOriginal)));


Or you can find the code here.

We will also downscale the image a little so that the recognition is fast.

You  can use following code sample from again Easy OCR Library

 private Bitmap getBitmapFromPath() {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 4;
        Bitmap bitmap = BitmapFactory.decodeFile(this.filePath, bmOptions);
        return bitmap;

Step 7 :

Final step. Recognize the text using the library API.

 private String scanImage(){
        TessBaseAPI baseApi = new TessBaseAPI();
        Log.d(Config.TAG, "Data path : " + FileUtils.getDirectory(this.directoryPath));
        baseApi.init(FileUtils.getDirectory(this.directoryPath) + "/", this.trainedDataCode);
        String recognizedText = baseApi.getUTF8Text();

        return recognizedText;

Again I would recommend using the Easy OCR Library if you are having facing any problem.

That library has many features :

  1. Very easy setup.
  2. Handles all the image processing part in a background thread.
  3. Provides very interface with relative callbacks for the functions of the library.


How to build Tesseract OCR library for Android Studio?

Star On GitHub

If you ever tried to create an OCR app for Android you must have stumbled upon the OCR library by Google Tesseract. And then the problems began.

To use the library in your project you first need to build it. But building the library to be compatible with gradle, which is the new build system for Android projects is little not so easily stated anywhere in the library manual.

When I tried to build the library, it took me freaking 9 hours to figure all the how tos?

So, here I am helping you to save your precious hours. (Don’t waste these watching late night infomercials for god’s sake! ).

Here we go.

Step 1 : 

The first step. Download the NDK. That is used to build the library.

Download it from here. It is around 300+ MB so keep your net plan nourished.

Step 2 : 

Better way to go is to use  a fork of Tesseract, Tess-Two. Tess-Two can be found on GitHub.

Execute following commands to build the library Tess-Two using NDK.

git clone git://github.com/rmtheis/tess-two tess
cd tess
cd tess-two
android update project --path .
ant release

We can live without building eyes-two for this time.

Building will take few minutes. After you have successfully built tess-two, give yourself a little treat. You are almost done.

Step 3 :

Now you are ready to use the library in your Android project.

Copy the tess-two folder (tess/tess-two), in the main folder of the application project.

Suppose name of your application is “MyApp” copy the folder at “MyApp/”.

Step 4 :

Now its time to play the trick. The library was build using ANT. But Android projects use Gradle these days. Interesting…

We need to add a “build.gradle” file at location “tess-two/”.

The build file can be found here.

Then include following line in project.settings file.

include ':tess-two'

Step 5 : 

Build the project and you are just one step away from being done.

Step 6 : 

The most important step. After completing steps 1-5, throw your hands up in the air! 😀 😀 You are now done!

Ready to harness the power of OCR.



5 Coolest features of Android Studio

Android Studio is out and stable now. It is always fun to try new tools. Right?

So far it has been around 2 months since I have been using Android Studio. And I guess it is the best time to select my personal choice of 5 coolest features of it.

If you want some technical or geeky feature list RTFM! This post is not meant for that.

1. Code preview scrolling


This is one of my favorite feature. In fact I loved this feature in intelliJ also. Scrolling through endless page of code becomes so easy and fluid with this feature. Claps! for the makers.

2. Inbuilt terminal


This just increases the comfort of accessing the terminal. Whether it is for adb commands or something else, an easy to access inbuilt terminal always helps.

3. Tab switcher


Working on Android projects includes working with many files including classes, layouts, values, styles etc.

What else can be useful more then a rocking tab switcher made for this purpose only.

4. Color and Image preview


As a developer one works with hex codes and ids of images. And then there are color and image previews just to make feel comfortable.

5. Smart code recognitioncode_inspection

Code inspection in Android Studio is pretty impressive. It guides you to maintain good quality code and instructs you like coding teacher.

That’s all folks! These were my favorite features of Android Studio. Of course these were not technical like better build system or performance stats, but at least these are more attractive to someone looking forward to use this amazing IDE.

Comment your favorite feature. I am excited to hear from you guys!