Android dagger kotlin example

Kotlin + MVP + Dagger 2 + Retrofit = Sample Android Application

I guess, it’s a classic post-title for these days :).

In this article, I would like to show how to implement MVP (Model-View-Presenter) pattern with using Dagger2 and also by Kotlin.

Design Patterns are very remarkable topic for mobile development. And as developers (not just android or mobile developers), we are trying to write cleaner and more testable codes and applications.

For the Android, with MVP, we are able to take most of logic out from the activities (or fragments). So that we can test it without using instrumentation tests. And with Dagger2, it is easier to apply concept of dependency injection.

So, this article/application will cover two design patterns: MVP and Dependency Injection. You may heard typicode, was used as server. It will be abstracted by using Retrofit and RxJava2 will be used to make requests it as observables which is another hot topic for mobile development.

Note: This article is not for starters. It does not answer questions like: What’s dagger or dagger in the past, dagger basics or Retrofit 101 etc.

If you are just interested in project, not the story, here is github repository:

ogulcan/kotlin-mvp-dagger2

kotlin-mvp-dagger2 — This example application implements MVP architecture using Kotlin, Dagger2, RxJava2 and also…

Let’s start with common discussions.

What is MVP ? Why do we need?

In Android we have a problem arising from the fact that activities are closely coupled to interface and data access mechanisms.

The Model-View-Presenter pattern allows to separate the presentation layer from the logic, so that everything about how the interface works is separated from how we represent it on screen.

MVP lets us to make views independent from data source and it will be easier to test each layer.

Libraries

As you may see from the title; I have used dagger2, retrofit, rxjava2 as libraries. I will not go into details about what’s dagger2 or retrofit.

Project Structure

Here is I have implemented MVP in Android. Let’s start with how project structure looks like:

This project structured into 5 packages:

  • api: Where Retrofit resides in.
  • di: Where dagger2 resides in aka dependency injection.
  • models: Data models.
  • ui: Activities and also with presenter and contract.
  • util: Some tweaks.

After the structure of project, I guess it would be more accurate to tell from the outside to the inside. Means: server → api →dependency injection (app) → ui (mvp).

Retrofit and Kotlin Data Classes

Typicode offers a simple server to us: Posts, users, albums. Depending on typicode, here is how retrofit interface should like:

Unlike Java, Kotlin has a great feature. Companion objects:

In Kotlin, an interface can have a companion object but it is not part of the contract that must be implemented by classes that implement the interface. It is just an object associated to the interface that has one singleton instance. So it is a place you can store things, but doesn’t mean anything to the implementation class.

Another great feature is data classes. It’s really easy to create pojos in Kotlin:

Читайте также:  Infuse pro 6 android

With these three lines (remember, each will be placed in its own separate file) compiler automatically derives the following members from all properties declared in the primary constructor.

Dependency Injection: Dagger2

So I have used an interface to declare api requests and data classes. Next step should be Dagger2 to implement dependency injection.

Dagger uses Components and Modules to define which dependencies will be injected in which objects.

This application will contain an activity (named as MainActivity) and several fragments. So we will need three components: ApplicationComponent, ActivityComponent (where presenter resides in) and FragmentComponent (where presenter and api service reside in).

Here is ApplicationComponent.kt:

It’s quite simple. It just injects application and provides it when needed. Let’s assume, if we want to use Calligraphy, Crashliytcs, Timber or Stetho, application module should inject those, too.

Activity/Fragment Component and Module are also similar to Application. Additionally, provides presenter and api service:

Here is I implemented Dagger on Application scope:

MVP Implementation

As mentioned above, MVP separates views from the logic. So as an initial step there is a BaseContract to abstract Presenter and View:

Since there are three layouts as Main and List and About, there are three contracts: MainContract, ListContact and AboutContract:

What is Contract?

Presenter and its corresponding View is defined in a Contract interface class, making the code more readable and the connection between the two easier to understand.

Main screen is an activity that controls fragment layout to show list or about. This is why view has just two functions.

List screen contains a list, as the name implies, that fetches data from server. During the request there will be a progress, if request fails there will be an error message, if request is okay data will be shown. And finally there will be a detail view for each item on the list.

Here is how ListContract looks like:

About view has just a text view that shows example message. Even it’s from xml or remote we should declare functionalities as well:

What is Presenter?

In MVP, Presenter retrieves the data from the Model, applies the UI logic and manages the state of the View, decides what to display and reacts to user input notifications from the View.

I will just show how List Presenter looks like:

For the last step, here is how to inject ActivityComponent on MainActivity:

What happens step by step once application start?

  • On BaseApp: Application Component will be initialized with using Dagger2. API service will be ready.
  • On MainActivity: Main Activity is default activity for the application. It contains a frame layout to represent list or about fragments. After dagger injection, view will be attached to presenter.
  • On ListFragment: After attachment, list fragment will be shown as default. It means that ListFragment will be shown. View of list fragment has also its presenter. So, posts list will be fetched from remote server.
  • On AboutFragment: If user taps option, about fragment will be shown with animation.

Thank you so much for coming so far!

If you want to know more about this sample application please see github repository.

If you liked this article, please share. So people can also read it.
Please get in touch with me via Github, Twitter or LinkedIn.

Источник

Kotlin Android Dagger2 Beginners Tutorial and Examples

Android Dagger2 Framework Tutorial and Examples

Dagger2 is a static compile-time dependency injection Framework for Java,Kotlin and Android.

It should actually be Dagger, Dagger2 simply implies the second version which was a complete re-write of the DI framework. The earlier version was created by Square. Dagger2 is now maintained by Google.

Читайте также:  Версия андроида с синим

Currently it’s one of the most popular Dependency Injection Frameworks and there are a bunch of tutorials and frameworks all over the internet.

However in this guide we will look at several examples starting from beginner level and slowly building to intermediate ones. To view the examples scroll down to the examples section.

Dagger2 Best Practices

Here are some best practices recommended in the Android Documentation regarding Dagger2

  • Use constructor injection with @Inject to add types to the Dagger graph whenever it’s possible. When it’s not:
    • Use @Binds to tell Dagger which implementation an interface should have.
    • Use @Provides to tell Dagger how to provide classes that your project doesn’t own.
  • You should only declare modules once in a component.
  • Name the scope annotations depending on the lifetime where the annotation is used. Examples include @ApplicationScope , @LoggedUserScope , and @ActivityScope .

Dagger2 Examples.

There are two examples: one in Java then one in Kotlin.

1. Hello World Dagger2 Example with SharedPreferences.

In this tutorial we want to introduce Dagger2 practically with a real world project. We will use the SharedPreferences to:

  1. Save Data From Edittext to SharedPreferences.
  2. Retrieve Data From SharedPreferences onto an EditText.

Our user interface comprises two edittexts where the user enters a username and his number and then clicks the save button. Then we get the value when the user clicks a get button. We rebind the value in the edittext.

Video Tutorial

Here’s the video tutorial.

(a). Build.gradle

We start by proceeding to our app level build.gradle and adding our dependencies. Dagger2 is a third party library maintained by Google. We have to fetch it from internet so we start by adding it’s dependency via Gradle.

  1. Once you’ve created your android application in android studio, navigate over to the build.gradle located in the app folder and move to the dependencies DSL.
  2. Replace them with the following code. You can replace the versions with the latest versions.

Here are the dependencies we’ve added:

  1. appcompat- A support library which will give us access to the AppCompatActivity class.
  2. constraint-layout – To give us the constraint layout.
  3. dagger2 – Our third party dependency injection framework. We also add our annotationProcessor. Remember Dagger2 is annotation based framework and we will be using several annotations to annotate our classes, interfaces, methods and fields.
(b). activity_main.xml

Next we come to activity_main.xml . This layout typically gets inflated into the MainActivity. In this layout we will construct our user interface using several elements all which are indirect or direct subclasses of the View class.

  1. LinearLayout– This will allow us arrange items linearly. In this case it is our container layout and we arrange it’s children vertically.
  2. TextView – Just to display our header.
  3. ImageView – To render our dummy image.
  4. EditText – To provide an interface for users to type data to be saved into our SharedPreferences.
  5. Button – When clicked we will either save to SharedPreferences or retrieve from them.

Here’s the full code:

(d). SharedPrefModule.java

This is our module class. Dagger2 has two main concepts, a module and a component. Basicly the module represents our dependencies while component represents a mapping between the module and it’s client/dependent object.

So we come create a module class here. But first we have to start by importing several objects:

  1. Context – required by our SharedPreferences class.
  2. SharedPreferences – We will return it’s instance as a dependency to the dependant.
  3. PreferenceManager – Will provide us our SharedPreference object.
  4. Singleton – will mark our object as a singleton. A singleton is a shared object. You can have one instance of a singleton object in memory.
  5. Module – will mark our SharedPrefModule class a module.
  6. Provides – Will mark our provider methods.
Читайте также:  Музыкальный плеер с визуализацией для андроид

Here are the methods we create:

  1. SharedPrefModule(Context context) : Our constructor. Will take a Context object and assign it to a local instance field.
  2. provideContext() – a method that wil return us a Context object if needed as a dependency.
  3. provideSharedPreferences() – a method that will return us a SharedPreferences object as a dependency to the dependant.

Here’s the full code. Take not that we mark our methods with Singleton and Provides annotations.

(d). MyComponent.java

This is our Dagger Component interface. A Component is a class that provides the mapping between a Module and a Dependent object. In this case will be mapping our SharedPrefModule to our MainActivity . So MainActivity is the dependnat object. It depends on the Module which is the SharedPrefModule . From it can get two methods injected into it as dependencies. Those are methods marked with @Provides annotation.

Here are some of our imports:

  1. Component – This is an annotation that will mark our interface as a daggger component.

Here are the annotations used:

  1. @Singleton – To mark our interface implementation object as a singleton. Only a single instance of that object can exist in memory.
  2. @Component – To mark our interface as a component. We provide it our modules/module. In this case we have only a single module. Suppose we had many we would have separated them with commas.

Here are our methods:

  1. void inject(..) – Will receive our dependant and map it to our module.

Here’s the full code:

(e). MainActivity.java

This is our MainActivity class. This will be our launcher activity. It is registered on the android manifest as it is an android component. Here are the things we will do here:

  1. Set our contentview for this activity.
  2. Initialize widgets like Buttons and Edittexts .
  3. Get data from edittext and insert them into shared preference.
  4. Retrieve data from sharedpreferences and bind them to edittexts.
  5. Initialize our DaggerComponent and pass it this activity’s instance.

[notice] Rebuild you project so that Dagger2 can generate us the DaggerMyComponent class. [/notice]

That DaggerMyComponent is our MyComponent implementation. We will build it and pass it our module. Then we also inject into it our dependant.

Building The Component

Here’s the method responsible for that:

How to save to SharedPreferences

Here’s the method for that

Example 2: Kotlin Android Dagger2 Example

Here’s another dead simple Dagger2 example written in Kotlin.

Step 1: Install Dagger2

Start by installing Dagger2 in your build.gradle , by specifying the dependency statement as follows:

At the top of the app/build.gradle do not forget to apply the kapt plugin:

Step 2: Design Layout

Add a TextView to your main XML layout:

activity_main.xml

Step 3: Write Code

Go to your main activity and add imports as follows. You may use AndroidX:

Create a Component known as MagicBox as an interface:

Then a class called info.Annotate the constructor with the @Inject property:

Then use them as follows in the MainActivity :

Here is the full code

MainActivity.kt

Reference

Download the code here

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Оцените статью