SlideShare a Scribd company logo
ARCHITECT ANDROID APPS
WITH MVP, DAGGER,
RETROFIT USING KOTLIN 
PRESENTED BY: DEVELOPINE.COM
CONTENTS
KOTLIN
ANDROID MVP
RETROFIT 2
DAGGER 2
JSON/GSON MAPPING - KOTLIN DATA
CLASSS
RECYCLERVIEW ADAPTER KOTLIN
WE WILL COVER ALL CONTENTS
IN THIS SEQUENCE-1
W h y u s e M V P D e s i g n P a t t e r n i n A n d r o i d .
H o w t o s t r u c t u r e A n d r o i d p r o j e c t f o r
i m p l e m e n t i n g M V P i n A n d r o i d a p p s u s i n g K o t l i n .
W h y w e n e e d D e p e n d e n c y I n j e c t i o n ( D I ) i n
A n d r o i d .
I n t r o t o D a g g e r 2 ( D I ) l i b r a r y i n A n d r o i d .
WE WILL COVER ALL CONTENTS
IN THIS SEQUENCE-2
S e t u p D a g g e r a n d R e t r o f i t G r a d l e d e p e n d e n c i e s .
I m p l e m e n t i n g D a g g e r 2 i n A n d r o i d u s i n g K o t l i n .
I m p l e m e n t i n g R e t r o f i t i n A n d r o i d u s i n g K o t l i n .
I m p l e m e n t i n g R e c y c l e r V i e w i n K o t l i n .
WWW.DEVELOPINE.COM
O R I G I N A L F U L L A R T I C L E C A N A L S O B E F O U N D O N
O U R B L O G :
h t t p : / / d e v e l o p i n e . c o m / b u i l d i n g - a n d r o i d - m v p - a p p - i n -
k o t l i n - u s i n g - d a g g e r - r e t r o f i t /
WHY NEED MVP DESIGN
PATTERN IN ANDROID
MVP (MODEL-VIEW-PRESENTER) in Android is used
to manage code in an efficient way.
MVP in Android facilitate separation of concern
and help to implement unit tests in Android
without Views.
THE MODEL LAYER
The Model layer is used to provide data to the
presenter, so presenter can pass it to view layer
for displaying data on UI.
Only Presenter can interact with Model, View
cannot directly communicate with Model.
Model is usually a Data Manager. It has to decide
or act to get data from API (Network), Shared
Preferences or SQlite database.
THE VIEW LAYER
Any Java or Kotlin class in Android app which can
make changes in UI comes under View.
Activities/Fragments/ Adapters/ Custom Views
are all Views in Kotlin.
Any user interaction on View layer e.g Button
click should be passed to the presenter.
The presenter will decide what action to
perfrom.
THE PRESENTER LAYER
The presenter is the middle man between view
and model.
View will only interact with presenter by calling
its functions.
Presenter is responsible to get data, perform any
operation on data like JSON parsing / cache data
and inform/update View by callings its functions
PROJECT PACKAGES
STRUCTURE FOR IMPLEMENTING
MVP AND DAGGER IN ANDROID-1
<< Create following packages in your Android App. >>
data-  (Add POJO/ DATA CLASSES in this package)
network- (Add API EndPoints , Retrofit Request Response
Interface in this package)
utils- (any utility classes or functions)
PROJECT PACKAGES
STRUCTURE FOR IMPLEMENTING
MVP AND DAGGER IN ANDROID-2
<< Create following packages in your Android App. >>
ui (Activities/Fragments)
service (Any service classes e.g Push Notification Handling)
di (Dependency Injection / Dagger2 Code will go here)
IMPLEMENTING MVP IN ANDROID
USING KOTLIN-1
We will Create new Activity PostActivity.kt in our Android
project inside ui package.
Which will make API call using Retrofit and show JSON
Response in RecyclerView using Kotlin.
PostActivity.kt is our View.
I will show you how View interacts with Model and Presenter
in MVP (Model-View-Presenter).
IMPLEMENTING MVP IN ANDROID
USING KOTLIN-2
Create PostView.kt Interface.
Create PostPresenter.kt Interface.
Create Presenter Implementation class PostPresenterImpl.kt
PostPresenterImpl.kt will implement interface
PostPresesnter.kt
IMPLEMENTING MVP IN ANDROID
USING KOTLIN-3
PostActivity.kt will have reference to the
PostPresenterImpl.kt class.
PostActivity.kt will implement PostView.kt
VIEW INTERFACE POSTVIEW.KT
//Presenter will call this method after getting list of posts from API.
// And will pass it List of Posts for displaying in RecyclerView.
interface PostView {
   fun showAllPosts(postList: List<PostData>)
}
PRESENTER INTERFACE
POSTPRESENTER.KT
- View will call this method from presenter.
- This method will load all posts from API using Retrofit2 and will send     
  response to the View by callings its method showAllPosts(lists) and will 
  pass list of posts for populating in RecyclerView using Kotlin.
interface PostPresenter {
   fun getAllPosts()
}
POSTACTIVITY.KT
class PostActivity : AppCompatActivity(), PostView {
    lateinit var postPresenter: PostPresenter
    override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_post) 
        
       postPresenter = PostPresenterImpl(this, application)
       postPresenter.getAllPosts()
}
override fun showAllPosts(postList: List<PostData>) { 
     // showing this postList in RecyclerView code will  be here.
       rv_post_list.layoutManager = LinearLayoutManager(this)
       rv_post_list.adapter = PostItemAdapter(postList, this)
 } }
POSTACTIVITY.KT LAYOUT FILE
ACTIVITY_POST.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.es.developine.ui.posts.PostActivity">
   <android.support.v7.widget.RecyclerView
       android:id="@+id/rv_post_list"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
</RelativeLayout>
POST PRESENTER
IMPLEMENTATION CLASS-1
PostPresenterImpl.kt is responsible to make API call.
Fetch list of posts using Retrofit Network Client.
Return list of posts to the PostActivity.kt. so PostActivity.kt
can display posts in RecyclerView using Kotlin.
I will be using dagger2 annotations in this class. we will
shortly cover Dependency Injection using Dagger2 in kotlin.
POST PRESENTER
IMPLEMENTATION CLASS-2
class PostPresenterImpl(var postView: PostView, var applicationComponent:
Application) : PostPresenter {
   
   @Inject
   lateinit var mNetworkApi: INetworkApi
   
   init {
       (applicationComponent as ApplicationClass).applicationComponent.inject(this)
   }
   
   override fun getAllPosts() {
       var allPosts = mNetworkApi.getAllPosts()
       allPosts.subscribeOn(IoScheduler()).observeOn(AndroidSchedulers.mainThread())
               .subscribe {
                   postView.showAllPosts(it)
               }
   }
}
LETS FIRST SETUP GRADLE
DEPENDENCIES FOR RETROFIT-2,
DAGGER-2 AND RECYCLERVIEW
dependencies {
   implementation 'com.android.support:recyclerview-v7:27.1.1'
   //retrofit_version = '2.4.0'
   implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
   implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
   implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
   implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
   implementation 'com.google.dagger:dagger-android:2.15'
   implementation 'com.google.dagger:dagger-android-support:2.15'
   // if you use the support libraries
   kapt 'com.google.dagger:dagger-android-processor:2.15'
   kapt 'com.google.dagger:dagger-compiler:2.15'
}
WHY NEED DEPENDENCY
INJECTION (DI) - 1 
- Dependency Injection (DI) is a design pattern in software engineering.
- It is a mechanism of providing required dependencies/objects to other classes
which need those dependencies.
For example, You have three classes in your project. ClassA, ClassB, ClassC.
ClassC needs an object of ClassA and ClassB.
Whereas ClassB needs an object of ClassA.
WHY NEED DEPENDENCY
INJECTION (DI) - 2
This means ClassC depends on ClassA and ClassB. And ClassB depends on
ClassA. (One class is dependent on another class / Dependency).
Now we don’t want to create objects of ClassA and ClassB inside ClassC. We
want to provide/pass initialized objects of ClassA and ClassB to ClassC.
For this purpose, we will inject (provide) required objects (dependencies) to
ClassC.
We will be using Dagger2 Android Library (using Kotlin language) for this
purpose.
INTRODUCTION TO DAGGER-2 IN
ANDROID 
Dagger2 is a framework which is used to provide/manage
dependencies in Android/Java.
It uses annotations.
Annotations in Dagger2 (DI):
@Provides
@Module
@Component
@Inject
@PROVIDES ANNOTATION IN
DAGGER2 - 1
@Provides annotation is used with methods which provide
the certain dependency.
For example below function, provideRetrofit is annotated
with @Provides (which means it will provide a dependency of
type Retrofit object).
@PROVIDES ANNOTATION IN
DAGGER2 - 2
// Retrofit object is available for dependency injection.
@Provides
fun provideRetrofit(gson: Gson): Retrofit {
   return
Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson))
           .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
           .baseUrl("https://jsonplaceholder.typicode.com/").build()
}
@MODULE ANNOTATION IN
DAGGER2 
- As mentioned earlier, We define methods in Module classes.
- We annotate module classes with @module annotation.
- And those methods provide the dependency.  
  A Module class is annotated with @Module annotation.
  
  And it can provide an object/dependencies to the component class
throgu functions annotated with @Provides.
@COMPONENT ANNOTATION IN
DAGGER2 - 1
A component is an Interface which is annotated with @Component
annotation.
It has all modules from which it can get dependencies and provide
those dependencies where required.
A component knows from where it can get dependencies (from which
modules).
And where it has to provide dependencies.
@COMPONENT ANNOTATION IN
DAGGER2 - 1
// NetModule is class which is annotated with @Module annotation. 
// NetModule class has functions annotated with @Provides (which return   
    dependency objects)
@Component(modules = [NetModule::class])
interface ApplicationComponent {
    // this means ApplicationComponent has to provide/inject
    // required dependencies in LoginPresenterImpl class.
   fun inject(mLoginPresenterImpl: LoginPresenterImpl)
}
CONCLUSION
We have learned about MVP (Model-View-Presenter) in Android.
We have learned how to architect our Android apps to achieve MVP in
Android using Kotlin.
We have learned about Dagger2 in Android using Kotlin.
We have learned how to provide Retrofit Dependecies using Dagger2
in Android (Kotlin).
To Access full article on Android MVP Dagger Retrofit RecyclerView
using Kotlin visit:
 
http://developine.com/building-android-mvp-app-in-kotlin-using-dagger-
retrofit/

More Related Content

What's hot

Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Sigma Software
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
Stfalcon Meetups
 
Dagger for dummies
Dagger for dummiesDagger for dummies
Dagger for dummies
Saúl Díaz González
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency Injections
GlobalLogic Ukraine
 
Hi AndroidAnnotations
Hi AndroidAnnotationsHi AndroidAnnotations
Hi AndroidAnnotations
Tsung-Yeh Lee
 
Angular
AngularAngular
Angular
sridhiya
 
Android Dagger2
Android Dagger2Android Dagger2
Android Dagger2
Monir Zzaman
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
rhemsolutions
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
Javad Hashemi
 
Enter the gradle
Enter the gradleEnter the gradle
Enter the gradle
Parameswari Ettiappan
 

What's hot (10)

Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
 
Dagger for dummies
Dagger for dummiesDagger for dummies
Dagger for dummies
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency Injections
 
Hi AndroidAnnotations
Hi AndroidAnnotationsHi AndroidAnnotations
Hi AndroidAnnotations
 
Angular
AngularAngular
Angular
 
Android Dagger2
Android Dagger2Android Dagger2
Android Dagger2
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
Enter the gradle
Enter the gradleEnter the gradle
Enter the gradle
 

Similar to Building android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Classes and RecyclerView using kotlin

How to code to code less
How to code to code lessHow to code to code less
How to code to code less
Anton Novikau
 
Ruby conf2012
Ruby conf2012Ruby conf2012
Ruby conf2012
Chandan Jog
 
Android architecture
Android architecture Android architecture
Android architecture
Trong-An Bui
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
Jose Manuel Pereira Garcia
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2
Sanket Shah
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
Muhammed Demirci
 
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React NativeGITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Indonesia
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
Gabor Varadi
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
React native bridge for iOS and android
 React native bridge for iOS and android React native bridge for iOS and android
React native bridge for iOS and android
Katy Slemon
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll
Uchiha Shahin
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
Chiew Carol
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
Designveloper
 
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
LogeekNightUkraine
 
Activity
ActivityActivity
Activity
NikithaNag
 
Activity
ActivityActivity
Activity
roopa_slide
 
Activity
ActivityActivity
Activity
NikithaNag
 
Activity
ActivityActivity
Activity
roopa_slide
 
How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.
Techugo
 

Similar to Building android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Classes and RecyclerView using kotlin (20)

How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Ruby conf2012
Ruby conf2012Ruby conf2012
Ruby conf2012
 
Android architecture
Android architecture Android architecture
Android architecture
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
 
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React NativeGITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React Native
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React native bridge for iOS and android
 React native bridge for iOS and android React native bridge for iOS and android
React native bridge for iOS and android
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
Pavlo Zhdanov "Java and Swift: How to Create Applications for Automotive Head...
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.
 

Recently uploaded

How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 

Recently uploaded (20)

How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 

Building android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Classes and RecyclerView using kotlin

  • 1. ARCHITECT ANDROID APPS WITH MVP, DAGGER, RETROFIT USING KOTLIN  PRESENTED BY: DEVELOPINE.COM
  • 2. CONTENTS KOTLIN ANDROID MVP RETROFIT 2 DAGGER 2 JSON/GSON MAPPING - KOTLIN DATA CLASSS RECYCLERVIEW ADAPTER KOTLIN
  • 3. WE WILL COVER ALL CONTENTS IN THIS SEQUENCE-1 W h y u s e M V P D e s i g n P a t t e r n i n A n d r o i d . H o w t o s t r u c t u r e A n d r o i d p r o j e c t f o r i m p l e m e n t i n g M V P i n A n d r o i d a p p s u s i n g K o t l i n . W h y w e n e e d D e p e n d e n c y I n j e c t i o n ( D I ) i n A n d r o i d . I n t r o t o D a g g e r 2 ( D I ) l i b r a r y i n A n d r o i d .
  • 4. WE WILL COVER ALL CONTENTS IN THIS SEQUENCE-2 S e t u p D a g g e r a n d R e t r o f i t G r a d l e d e p e n d e n c i e s . I m p l e m e n t i n g D a g g e r 2 i n A n d r o i d u s i n g K o t l i n . I m p l e m e n t i n g R e t r o f i t i n A n d r o i d u s i n g K o t l i n . I m p l e m e n t i n g R e c y c l e r V i e w i n K o t l i n .
  • 5. WWW.DEVELOPINE.COM O R I G I N A L F U L L A R T I C L E C A N A L S O B E F O U N D O N O U R B L O G : h t t p : / / d e v e l o p i n e . c o m / b u i l d i n g - a n d r o i d - m v p - a p p - i n - k o t l i n - u s i n g - d a g g e r - r e t r o f i t /
  • 6. WHY NEED MVP DESIGN PATTERN IN ANDROID MVP (MODEL-VIEW-PRESENTER) in Android is used to manage code in an efficient way. MVP in Android facilitate separation of concern and help to implement unit tests in Android without Views.
  • 7. THE MODEL LAYER The Model layer is used to provide data to the presenter, so presenter can pass it to view layer for displaying data on UI. Only Presenter can interact with Model, View cannot directly communicate with Model. Model is usually a Data Manager. It has to decide or act to get data from API (Network), Shared Preferences or SQlite database.
  • 8. THE VIEW LAYER Any Java or Kotlin class in Android app which can make changes in UI comes under View. Activities/Fragments/ Adapters/ Custom Views are all Views in Kotlin. Any user interaction on View layer e.g Button click should be passed to the presenter. The presenter will decide what action to perfrom.
  • 9. THE PRESENTER LAYER The presenter is the middle man between view and model. View will only interact with presenter by calling its functions. Presenter is responsible to get data, perform any operation on data like JSON parsing / cache data and inform/update View by callings its functions
  • 10. PROJECT PACKAGES STRUCTURE FOR IMPLEMENTING MVP AND DAGGER IN ANDROID-1 << Create following packages in your Android App. >> data-  (Add POJO/ DATA CLASSES in this package) network- (Add API EndPoints , Retrofit Request Response Interface in this package) utils- (any utility classes or functions)
  • 11. PROJECT PACKAGES STRUCTURE FOR IMPLEMENTING MVP AND DAGGER IN ANDROID-2 << Create following packages in your Android App. >> ui (Activities/Fragments) service (Any service classes e.g Push Notification Handling) di (Dependency Injection / Dagger2 Code will go here)
  • 12. IMPLEMENTING MVP IN ANDROID USING KOTLIN-1 We will Create new Activity PostActivity.kt in our Android project inside ui package. Which will make API call using Retrofit and show JSON Response in RecyclerView using Kotlin. PostActivity.kt is our View. I will show you how View interacts with Model and Presenter in MVP (Model-View-Presenter).
  • 13. IMPLEMENTING MVP IN ANDROID USING KOTLIN-2 Create PostView.kt Interface. Create PostPresenter.kt Interface. Create Presenter Implementation class PostPresenterImpl.kt PostPresenterImpl.kt will implement interface PostPresesnter.kt
  • 14. IMPLEMENTING MVP IN ANDROID USING KOTLIN-3 PostActivity.kt will have reference to the PostPresenterImpl.kt class. PostActivity.kt will implement PostView.kt
  • 15. VIEW INTERFACE POSTVIEW.KT //Presenter will call this method after getting list of posts from API. // And will pass it List of Posts for displaying in RecyclerView. interface PostView {    fun showAllPosts(postList: List<PostData>) }
  • 16. PRESENTER INTERFACE POSTPRESENTER.KT - View will call this method from presenter. - This method will load all posts from API using Retrofit2 and will send        response to the View by callings its method showAllPosts(lists) and will    pass list of posts for populating in RecyclerView using Kotlin. interface PostPresenter {    fun getAllPosts() }
  • 17. POSTACTIVITY.KT class PostActivity : AppCompatActivity(), PostView {     lateinit var postPresenter: PostPresenter     override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_post)                  postPresenter = PostPresenterImpl(this, application)        postPresenter.getAllPosts() } override fun showAllPosts(postList: List<PostData>) {       // showing this postList in RecyclerView code will  be here.        rv_post_list.layoutManager = LinearLayoutManager(this)        rv_post_list.adapter = PostItemAdapter(postList, this)  } }
  • 18. POSTACTIVITY.KT LAYOUT FILE ACTIVITY_POST.XML <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.es.developine.ui.posts.PostActivity">    <android.support.v7.widget.RecyclerView        android:id="@+id/rv_post_list"        android:layout_width="match_parent"        android:layout_height="match_parent" /> </RelativeLayout>
  • 19. POST PRESENTER IMPLEMENTATION CLASS-1 PostPresenterImpl.kt is responsible to make API call. Fetch list of posts using Retrofit Network Client. Return list of posts to the PostActivity.kt. so PostActivity.kt can display posts in RecyclerView using Kotlin. I will be using dagger2 annotations in this class. we will shortly cover Dependency Injection using Dagger2 in kotlin.
  • 20. POST PRESENTER IMPLEMENTATION CLASS-2 class PostPresenterImpl(var postView: PostView, var applicationComponent: Application) : PostPresenter {        @Inject    lateinit var mNetworkApi: INetworkApi        init {        (applicationComponent as ApplicationClass).applicationComponent.inject(this)    }        override fun getAllPosts() {        var allPosts = mNetworkApi.getAllPosts()        allPosts.subscribeOn(IoScheduler()).observeOn(AndroidSchedulers.mainThread())                .subscribe {                    postView.showAllPosts(it)                }    } }
  • 21. LETS FIRST SETUP GRADLE DEPENDENCIES FOR RETROFIT-2, DAGGER-2 AND RECYCLERVIEW dependencies {    implementation 'com.android.support:recyclerview-v7:27.1.1'    //retrofit_version = '2.4.0'    implementation "com.squareup.retrofit2:retrofit:$retrofit_version"    implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"    implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'    implementation 'com.google.dagger:dagger-android:2.15'    implementation 'com.google.dagger:dagger-android-support:2.15'    // if you use the support libraries    kapt 'com.google.dagger:dagger-android-processor:2.15'    kapt 'com.google.dagger:dagger-compiler:2.15' }
  • 22. WHY NEED DEPENDENCY INJECTION (DI) - 1  - Dependency Injection (DI) is a design pattern in software engineering. - It is a mechanism of providing required dependencies/objects to other classes which need those dependencies. For example, You have three classes in your project. ClassA, ClassB, ClassC. ClassC needs an object of ClassA and ClassB. Whereas ClassB needs an object of ClassA.
  • 23. WHY NEED DEPENDENCY INJECTION (DI) - 2 This means ClassC depends on ClassA and ClassB. And ClassB depends on ClassA. (One class is dependent on another class / Dependency). Now we don’t want to create objects of ClassA and ClassB inside ClassC. We want to provide/pass initialized objects of ClassA and ClassB to ClassC. For this purpose, we will inject (provide) required objects (dependencies) to ClassC. We will be using Dagger2 Android Library (using Kotlin language) for this purpose.
  • 24. INTRODUCTION TO DAGGER-2 IN ANDROID  Dagger2 is a framework which is used to provide/manage dependencies in Android/Java. It uses annotations. Annotations in Dagger2 (DI): @Provides @Module @Component @Inject
  • 25. @PROVIDES ANNOTATION IN DAGGER2 - 1 @Provides annotation is used with methods which provide the certain dependency. For example below function, provideRetrofit is annotated with @Provides (which means it will provide a dependency of type Retrofit object).
  • 26. @PROVIDES ANNOTATION IN DAGGER2 - 2 // Retrofit object is available for dependency injection. @Provides fun provideRetrofit(gson: Gson): Retrofit {    return Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson))            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())            .baseUrl("https://jsonplaceholder.typicode.com/").build() }
  • 27. @MODULE ANNOTATION IN DAGGER2  - As mentioned earlier, We define methods in Module classes. - We annotate module classes with @module annotation. - And those methods provide the dependency.     A Module class is annotated with @Module annotation.      And it can provide an object/dependencies to the component class throgu functions annotated with @Provides.
  • 28. @COMPONENT ANNOTATION IN DAGGER2 - 1 A component is an Interface which is annotated with @Component annotation. It has all modules from which it can get dependencies and provide those dependencies where required. A component knows from where it can get dependencies (from which modules). And where it has to provide dependencies.
  • 29. @COMPONENT ANNOTATION IN DAGGER2 - 1 // NetModule is class which is annotated with @Module annotation.  // NetModule class has functions annotated with @Provides (which return        dependency objects) @Component(modules = [NetModule::class]) interface ApplicationComponent {     // this means ApplicationComponent has to provide/inject     // required dependencies in LoginPresenterImpl class.    fun inject(mLoginPresenterImpl: LoginPresenterImpl) }
  • 30. CONCLUSION We have learned about MVP (Model-View-Presenter) in Android. We have learned how to architect our Android apps to achieve MVP in Android using Kotlin. We have learned about Dagger2 in Android using Kotlin. We have learned how to provide Retrofit Dependecies using Dagger2 in Android (Kotlin). To Access full article on Android MVP Dagger Retrofit RecyclerView using Kotlin visit:   http://developine.com/building-android-mvp-app-in-kotlin-using-dagger- retrofit/