Android App Development with Dependencies
- Description
- Curriculum
- FAQ
- Reviews
A complete course on Android App Development using Android Dependencies
In this course you are going to learn about top android Dependencies, like OkHttp retrofit,gson,OTTO, rxjava2,glide,butterknife,realm,dagger2 and your will get a chance to learn how to use these dependencies with MVVM design pattern that will change your way of app development. After enrolling and watching the whole course you will able to develop, reliable,fast and bug free android apps that bring money and client satisfactions.
-
1What is OkHttp ?Video lesson
OkHTTP is an open source modern, fast and efficient Http client to work with HTTP protocol for Android and support Kotlin, and Java.If we use OkHttp in android apps then developer does not require rewriting the network code in your program.
-
2OkHttp Overview?Video lesson
OkHTTP is an open source project designed to be a smart HTTP client. It's easy to use and It removes the need for network testing, recovering from common connection problems. Using a library instead of the raw sdk code is a good practice.
OkHttp comes with advanced options like Connection pooling , compression, and helps recovering from the network problems. For example If your server is configured with multiple IP addresses, OkHttp will automatically try the next IP when the first IP connection fails. OkHttp also handles proxy server issues and SSL handshake failures.
What we can do with OkHttp Client ?1 Sending and Receiving Network Requests
and request can be
2 Synchronous Network Calls
3 Asynchronous Network Calls
4 Updating Views on UIThread
5 Processing Network Responses
6 Processing JSON data
7 Processing JSON data with Gson
8 Sending Authenticated Requests
9 Caching Network Responses
10 Upload And Download Files
11 Custom Header for Networking Requests
12 Networking Call TimeOut
13 Working with Websockets
14 Interceptors
-
3OkHttp build Setup and First Network RequestVideo lesson
Step 1
Makes sure to enable the use of the Internet permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
Step 2
To include the latest version of OkHttp in your app’s gradle file.
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
Now I will show you the code , how to
To Sending and Receiving Network Requests
Now, it’s time to write the Java code to make the Network Request by using the OkHttp API. First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class.
// should be a singletonOkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://theappsfirm.com/helloworld.txt").build();
-
4OkHttp Get RequestVideo lesson
This peace of code shows how to send http get request with OkHttp. To make an http get request call, you need to create Request object by using Request.Builder. Then invoke newCall method on OkHttpClient object passing the Request object. Finally, call execute() method on Call object to make http get request and receive response. This service call returns response in JSON format. Once you get JSON string from response by calling response.body().string(), you can use JSONObject of gson for parsing it.
-
5OkHttp Post RequestVideo lesson
To add post data to Request as key value pairs like data you need to use FormBody.Builder, add post parameters to it, and create RequestBody as shown below.Then invoke execute method on OkHttpClient object passing the Request object. Finally, call execute() method on Call object to make http get request and receive response.
-
6OkHttp Synchronous and Asynchronous CallVideo lesson
OkHttp Synchronous and Asynchronous Call
Synchronous:
If an API call is synchronous, it means that code execution will block (or wait) for the API call to return before continuing. This means that until a response is returned by the API, your application will not execute any further, which could be perceived by the user as latency or performance lag in your app. Making an API call synchronously can be beneficial, however, if there if code in your app that will only execute properly once the API response is received.
Asynchronous:
Asynchronous calls do not block (or wait) for the API call to return from the server. Execution continues on in your program, and when the call returns from the server, a "callback" function is executed.
Callback
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
-
7OkHttp Downloading and Uploading filesVideo lesson
OkHttp Downloading and Uploading File
To upload files to the server, first you need to get read external storage permission in android app.
And then you need to create a file object and get the absolute path
create a OkHttp client object and prepare request body for request to server.
What is multipart?
Multipart request is an HTTP request that HTTP clients construct to send files and data over to a HTTP Server.It is commonly used by browsers and HTTP clients to upload files to the server.
Multipart has Content-Type and it means when you send any request
to server than you need to tell the server what kind of request you need to make.
for example request could be form-data or Json data.
-
8Okhttp Lab WorkVideo lesson
-
9what is retrofit ?Video lesson
What is Retrofit ?
Retrofit is a type-safe HTTP REST client for Android and support Java and kotlin . Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Retrofit is type-safe because it ensures that every function called or operation defined is not performed until it verifies the actual type of data passed. This ‘verification stage’ or ‘type-checking’ takes place either at compile time or at runtime for code verification.
What is a REST meaning??
REST is a client-server architecture. REST stands for Representational State Transfer. It can be defined as a set of architectural standards, principles and guidelines for communication and to perform networking tasks between interoperable systems.
Retrofit is an example of a REST Client. It is a popular choice for android for managing HTTP requests and web service integration. Retrofit makes it relatively easy to retrieve and upload JSON or other data structure via a REST based web service. Implementation of these webservice can include: GET, POST, PUT, DELETE, PATCH, TRACE, OPTIONS, CONNECT.
Just on a side note. Retrofit use OkHttp underline to make request to server.
-
10Retrofit build setup ?Video lesson
Retrofit Build Setup
Create a new project in Android Studio and Open build.gradle and add Retrofit, Gson dependencies. Since we are working with network operations we need to add INTERNET permissions in the AndroidManifest.xml file.
compile 'com.squareup.retrofit2:retrofit:2.4.0'
-
11Retrofit HTTP client in your Android applicationVideo lesson
Retrofit Configuration ?
let's talk about how retrofit work.To work with Retrofit you basically need the three classes.
1 . Model class
2 . Interfaces Class
3 . Retrofit.Builder class
Retrofit create one api interface and retrofit builder object to create request to server. For now only keep in mind that Model class is used as a JSON model and Interfaces Class defined inside api endpoints and Retrofit Builder class use model class and interface class to specify the base URL for the Api service. That's all you need to know at this point.
Retrofit Annotations ?
Before I move to the next step , just look at this api interface class. you will notice some annotations. and let me explain first what are these.
In Api Interface class Each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and the parameters of this method can also have special annotations (@Query, @Path, @Body etc.)
Take a look to other annotations and what they offer when we use in api calls:
@Path – variable substitution for the API endpoint. For example movie id will be swapped for{id} in the URL endpoint.
@Query – specifies the query key name with the value of the annotated parameter.
@Body – payload for the POST call
@Header – specifies the header with the value of the annotated parameter
What is Retrofit Api Interface and how it works?
Retrofit create an interface class and inside defined endpoints using special retrofit annotations to call apis with encode details about the parameters and request method.
Every method of an interface represents one possible API call. It must have HTTP annotation (GET, POST, etc.) to specify the request type and the relative URL. The return value wraps the response in a Call object with the type of the expected result.
@GET("users")
Call<List<User>> getUsers();
So let me show how these annotations help to make life easy to change data or append data in api urls.
See this example how @Path annotation help to replace the value within {} inside URL, the value of name parameter is bound to the specific replacement block.
@GET("users/{name}/commits")
Call<List<Commit>> getCommitsByName(@Path("name") String name);
Query parameters automatically added at the end of the URL.
@GET("users")
Call<User> getUserById(@Query("id") Integer id);
The @Body annotation tells Retrofit to use the object as the request body for the call.
@POST("users")
Call<User> postUser(@Body User user)
How Retrofit builder works ?
Retrofit.Builder class - Instance which uses the interface and the Builder API to allow defining the URL endpoint for the HTTP operations.
-
12Retrofit Lab WorkVideo lesson
-
13What is Gson and how to setup ?Video lesson
Gson
What is Gson Dependency ?
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Gson build Setup ?
Before we can get started, we need to pull in the Gson library to our project. At the time of writing, the latest version is 2.8.5. If you're using Gradle, add the following line:
implementation 'com.google.code.gson:gson:2.8.5'
-
14What is Gson Annotation ?Video lesson
What is @Expose annotation in Gson ?
The GSON @Expose annotation (com.google.gson.annotations.Expose) can be used to mark a field to be exposed or not (included or not) when an object is serialized or deserialized. The @Expose annotation can take two parameters. Each parameter is a boolean which can take either the value true or false.
@Expose(serialize = true);
The @Expose annotation serialize parameter specifies if the field annotated with the @Exposeannotation should be included when the owning object is serialized. The deserialize parameter specifies whether that field should be read when the owning object is deserialized.
-
15Gson Lab work.Video lesson
-
16OTTO Event Bus and its Components ?Video lesson
Otto Event Bus is an Android Library that helps developers to communicate between Android Activity and Fragment and vice-versa.
To use Otto, create a singleton instance of the Bus class and provide access to it for your Android components. This is typically done in the Application object of your Android application.Bus bus = new Bus(ThreadEnforcer.MAIN);
-
17OTTO setup ?Video lesson
OTTO Components ?
Publishers - classes that publish events
Subscribers - classes that listen/subscribe to events
Bus - the middle man that manages the events
Events - can be anything - a button click event, a successful server response event, a database loading failure event, etc which can be represented by POJOs
-
18OTTO Lab WorkVideo lesson
-
19RxJava and its Basic Building BlocksVideo lesson
What is Reactive programming ?
Reactive programming is a general programming term that is focused on reacting to changes, such as data values or events. A callback is an approach to reactive programming done imperatively.
Rx is built on the Observer pattern. The key elements are the Observer and the Subscriber. Observable is the base type. This class contains the main part of the Rx implementation and includes all basic operators.
By the end of this series you’ll have mastered all the RxJava 2 essentials so you can start creating highly reactive apps that can process a wide range of synchronous and asynchronous data — all using code that’s more concise and manageable than you’d typically be able to achieve with Java alone.
first, I’ll be covering what RxJava is and the key benefits it offers Android developers. We’ll also take an in-depth look at the core components of any RxJava project: Observers, Observables, and subscriptions. By the end of this tutorial, you'll have created a simple "Hello World"-style application that includes all of these core components.
The other major building blocks of RxJava are operators, so in part two I’ll be exploring the different ways you can use operators to transform, combine, filter and manipulate your application’s data.
What is RxJava2 ?
RxJava is a library that lets you create applications in the reactive programming style. At its core, reactive programming provides a clean, efficient way of processing and reacting to streams of real-time data, including data with dynamic values.
RxJava pretty much treats everything as a stream of data — everything from variables to properties, caches, and even user input events like clicks and swipes.
RxJava2 Build Setup ?
Using RxJava 2.0 Library in your application
Add this in your build.gradle
compile 'io.reactivex.rxjava2:rxjava:2.2.2'
If you are using RxAndroid also, then add the following
compile 'io.reactivex.rxjava2:rxandroid:2.1.0'
RxJava2 Basic Building Blocks ?
So at a very high level, RxJava is all about:
observables representing sources of data
subscribers (or observers) listening to the observables
Observables
Observables are the sources for the data. Usually they start providing data once a subscriber starts listening. An observable may emit any number of items (including zero items). It can terminate either successfully or with an error. Sources may never terminate, for example, an observable for a button click can potentially produce an infinite stream of events.
Subscribers
An observable can have any number of subscribers. If a new item is emitted from the observable, the onNext() method is called on each subscriber. If the observable finishes its data flow successful, the onComplete() method is called on each subscriber. Similar, if the observable finishes its data flow with an error, the onError() method is called on each subscriber.
-
20Observable types and States With SchedulersVideo lesson
Observable types ?
There are different types of Observers.
Flowable <> Observer
Flowable comes to picture when there is a case that the Observable is emitting huge numbers of values which can’t be consumed by the Observer.
In this case, the Observable needs to skip some values on the basis of some strategy otherwise it will throw an exception.
The Flowable Observable handles the exception with a strategy.
The strategy is called BackPressureStrategy and the exception is called MissingBackPressureException.
Observable <> Observer
This is the simplest Observable which can emit more than one value.
Example use-case: Let’s say you are downloading a file and you have to push the current status of download percentage. Here, you will have to emit more than one value.Creating a simple Observable
Single <> SingleObserver
Single is used when the Observable has to emit only one value like a response from a network call.
Maybe <> MaybeObserver
Maybe is used when the Observable has to emit a value or no value.
Completable <> CompletableObserver
Completable is used when the Observable has to do some tasks without emitting a value.
Now, you can think about when to use which Observable depending upon your use-cases.
RxJava2 Schedulers ?
Schedulers are used in multi-threading environment to work with Observable operators.
Scheduler are used to schedule how chain of operators will apply to different threads.
There are following types of Schedulers available in RxJava −
Schedulers
RxJava Schedulers is all about managing thread at low level. They provide high-level constructs to manage concurrency and deal with details by itself. They create workers who are responsible for scheduling and running code. By default RxJava will not introduce concurrency and will run the operations on the subscription thread.
Sr.No.
Scheduler & Description
1
Schedulers.computation()
Creates and returns a Scheduler intended for computational work. Count of threads to be scheduled depends upon the CPUs present in the system. One thread is allowed per CPU. Best for event-loops or callback operations.
2
Schedulers.io()
Creates and returns a Scheduler intended for IO-bound work. Thread pool may extend as needed.
3
Schedulers.newThread()
Creates and returns a Scheduler that creates a new Thread for each unit of work.
4
Schedulers.trampoline()
Creates and returns a Scheduler that queues work on the current thread to be executed after the current work completes.
4
Schedulers.from(java.util.concurrent.Executor executor)
Converts an Executor into a new Scheduler instance.
Observable States ?
The Observer has 4 interface methods to know the different states of the Observable.
onSubscribe(): This method is invoked when the Observer is subscribed to the Observable.
onNext(): This method is called when a new item is emitted from the Observable.
onError(): This method is called when an error occurs and the emission of data is not successfully completed.
onComplete(): This method is called when the Observable has successfully completed emitting all items.
-
21RxJava2 Operator TypesVideo lesson
RxJava2 Operator Types ?
Operators are basically a set of functions that can operate on any observable and defines the observable, how and when it should emit the data stream.
it allows you to manipulate the data emitted by Observables. Basically, operators tells Observable, how to modify the data and when to emit the data. Using the operators you can modify, merge, filter or group the data streams.
-
22RxJava Lab WorkVideo lesson
-
23What is Glide ? and how it save images on Sd Card.Video lesson
what is Glide and Glide Features ?
Glide is a famous image loading and management open source library contributed by Bump Technologies.
Glide is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.
Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs. Glide includes a flexible API that allows developers to plug in to almost any network stack. By default Glide uses a custom HttpUrlConnection based stack, but also includes utility libraries plug in to Google's Volley project or Square's OkHttp library instead.
Glide's primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.
Glide Build Setup ?
After upgrade android studio sdk, you need to add below dependencies in our project build.gradle file dependencies section.
implementation 'com.github.bumptech.glide:glide:4.6.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
Glide Request Builder ?
Most options in Glide can be applied directly on the RequestBuilder object returned by Glide.with()
Available options include (among others):
Placeholders
Transformations
Caching Strategies
Component specific options, like encode quality, or decode Bitmap configurations.
For example, to apply a CenterCrop Transformation, you’d use the following:
Glide.with(fragment)
.load(url)
.centerCrop()
.into(imageView);
RequestBuilder is the backbone of the request in Glide and is responsible for bringing your options together with your requested url or model to start a new load.
Use RequestBuilder to specify:
The type of resource you want to load (Bitmap, Drawable etc)
The url/model you want to load the resource from
The view you want to load the resource into
Any RequestOption object(s) you want to apply
Any TransitionOption object(s) you want to apply
Any thumbnail() you want to load.
You obtain a RequestBuilder by calling Glide.with() and then one of the as methods:
RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).asDrawable();
Or by calling Glide.with() and then load():
RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).load(url);
Glide Request Listner ?
RequestListener to monitor the resource load. It's best to create a single
* instance of an exception handler per type of request (usually activity/fragment) rather than
* pass one in per request to avoid some redundant object allocation.
onLoadFailed
onResourceReady
Glide Caching Strategy ?
After we've looked at loading, displaying and manipulating images, we'll move on to optimize the process. One of the fundamental features of successful and efficient image loading is caching.
By default, Glide checks multiple layers of caches before starting a new request for an image:
Active resources - Is this image displayed in another View right now?
Memory cache - Was this image recently loaded and still in memory?
Resource - Has this image been decoded, transformed, and written to the disk cache before?
Data - Was the data this image was obtained from written to the disk cache before?
The first two steps check to see if the resource is in memory and if so, return the image immediately. The second two steps check to see if the image is on disk and return quickly, but asynchronously.
Glide transformations ?
An Android transformation library providing a variety of image transformations for Glide.
Transformations in Glide take a resource, mutate it, and return the mutated resource. Typically transformations are used to crop, or apply filters to Bitmaps, but they can also be used to transform animated GIFs, or even custom resource types.
Built in types
Glide includes a number of built in transformations, including:
CenterCrop
FitCenter
CircleCrop
Glide Placeholder and Error handling ?
Glide allows users to specify three different placeholders that are used under different circumstances:
placeholder
error
fallback
Placeholders are Drawables that are shown while a request is in progress. When a request completes successfully, the placeholder is replaced with the requested resource. If the requested resource is loaded from memory, the placeholder may never be shown. If the request fails and an error Drawable is not set, the placeholder will continue to be displayed. Similarly if the requested url/model is null and neither an error Drawable nor a fallback Drawable are set, the placeholder will also continue to be displayed.
Glide.with(fragment)
.load(url)
.placeholder(R.drawable.placeholder)
.into(view);
Or:
Glide.with(fragment)
.load(url)
.placeholder(new ColorDrawable(Color.BLACK))
.into(view);
Error
Error Drawables are shown when a request permanently fails. Error Drawables are also shown if the requested url/model is null and no fallback Drawable is set
Glide.with(fragment)
.load(url)
.error(R.drawable.error)
.into(view);
Or:
Glide.with(fragment)
.load(url)
.error(new ColorDrawable(Color.RED))
.into(view);
Fallback
Fallback Drawables are shown when the requested url/model is null. The primary purpose of fallback Drawables is to allow users to indicate whether or not null is expected. For example, a null profile url may indicate that the user has not set a profile photo and that a default should be used. However, null may also indicate that meta-data is invalid or couldn’t be retrieved. By default Glide treats null urls/models as errors, so users who expect null should set a fallback Drawable.
Glide.with(fragment)
.load(url)
.fallback(R.drawable.fallback)
.into(view);
-
24Glide Lab ExampleVideo lesson
-
25what is ButterKnife and how to use in Android App.Video lesson
ButterKnife
what is ButterKnife ?
Butterknife is a lightweight library to inject views into Android components. It uses annotation processing.Butterknife uses annotation processing to generated modified Java classes based on your annotations. Annotation processing is a tool build in javac for scanning and processing annotations at compile time.
ButterKnife Build Setup ?
Add the com.jakewharton:butterknife in its latest version as compile dependency build.gradle file.
ButterKnife Annotations ?
The @BindView annotation allow to inject views and performs the cast to the correct type for you. The @@OnClick(R.id.yourid) annotation allows to add OnClickListener to a view. You can optional define the method parameter of the view in case you want it injected.
ButterKnife View Binding ?
View binding with Butterknife can be performed in an activity, view or even dialog. But before adding annotations we need to initialize Butterknife library. We initialize it by specifying a target component to search for annotations and root view to search views. Eliminate findViewById calls by using @BindView on fields.
all the butterknife annotations will be available to import. To begin with, we’ll see how to use @BindView and @OnClick annotations.
ButterKnife Binding resources ?
We first bind the views using the annotation @BindView and then let ButterKnife know about it by just writing ButterKnife.bind(this) in onCreate() of our Activity or ButterKnife.bind(this, inflatedView) in onCreateView() of our Fragments.
ButterKnife Event Listeners ?
Now as the number of views increase in our layout so does the above code. For every new view we need to initialize using findViewById() and then add an anonymous class if we need to listen for any events. This approach is tiring and adds a lot of boilerplate code in our application. Now for the same views we use Butterknife library to initialize and attach click listeners.
Look at the code snippet below.
@OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
-
26ButterKnife Lab ExampleVideo lesson
-
27What is Realm and how to use in android Apps.Video lesson
Realm
what is Realm ? and why use Realm ?
Realm is a cross-platform mobile database solution designed for mobile applications that you can integrate with your iOS projects. Unlike wrappers around Core Data, Realm doesn’t rely on Core Data or even an SQLite back end.
Realm Build Setup ?
To use Realm, you need to add the Realm gradle plugin to your dependencies:
dependencies {
classpath "io.realm:realm-gradle-plugin:4.3.1"
}
Realm initialize and Configuration ?
Create an application class where Realm is initialized.
Realm.init(this)
Realm.setDefaultConfiguration(
RealmConfiguration.Builder()
.deleteIfMigrationNeeded()
.build())
Realm Model Creation ?
Define your model class by extending RealmObject. It is similar to your everyday POJO classes.
Realm Transaction and Queries ?
While reading data from a Realm is very simple, as you will see in the next step, writing data to it is slightly more complex. Realm is ACID compliant and to ensure atomicity and consistency, Realm forces you to execute all write operations inside a transaction.
To start a new transaction, use the beginTransaction method. Similarly, to end the transaction, use the commitTransaction method.
Here’s how you would create and save an instance of the Country class:
```java myRealm.beginTransaction();
// Create an object
Country country1 = myRealm.createObject(Country.class);
// Set its fields
country1.setName("Norway");
country1.setPopulation(5165800);
country1.setCode("NO");
myRealm.commitTransaction(); ```
You might have noticed that country1 was not created using the constructor of the Country class. For a Realm to manage an instance of a RealmObject, the instance must be created using the createObjectmethod.
Realm Writing Data ?
Realm offers a very intuitive and fluent API for creating queries. To create a query, use the where method of the relevant Realm object and pass the class of the objects you are interested in. After creating the query, you can fetch all results using the findAll method, which returns a RealmResults object. In the following example, we fetch and print all objects of type Country:
```java RealmResults results1 = myRealm.where(Country.class).findAll();
for(Country c:results1) { Log.d(“results1”, c.getName()); }
Realm Update Data ?
Using realm you can directly update row just same as we set some value to pojo object :
object.setsomecolumnvalue1name(“sk”),object.setsomecolumnvalue2name(“abc”) etc,then you can pass that pojo object to realm.copyToRealmOrUpdate(object)
method in overridden method execute (Realm realm)
Realm Delete Data ?
You can delete the results of a query from the Realm but you must do so in a write transaction.
deleteFromRealm() - deletes the object from our Realm
-
28Realm Lab WorkVideo lesson
-
29What is Dagger2 and How it works?Video lesson
What is Dagger2 ?
Dagger2 is a dependency injection framework. It provides an allegiant solution to tight coupling problem. Dagger2 based on the Java Specification Request. It uses code generation based on annotations.
Dagger 2 uses the following annotations:
@Module and @Provides: define classes and methods which provide dependencies
@Inject: request dependencies. Can be used on a constructor, a field, or a method
@Component: enable selected modules and used for performing dependency injection
Dagger2 Components
Dagger2 Sample Application
Now we will demonstrate how to implement dependency injection using Dagger2 in Android. You have to follow the following steps to setup dependency injection in own project.
Add dependency in build.gradle
We will open the Android Studio and will open app module build.gradle add implementation in dependencies and just click on sync now.
implementation 'com.google.dagger:dagger-android:2.20'
implementation 'com.google.dagger:dagger-android-support:2.20'
// if you use the support libraries
annotationProcessor 'com.google.dagger:dagger-android-processor:2.20'
annotationProcessor 'com.google.dagger:dagger-compiler:2.20'
Following are the basic annotations used in Dagger 2:
@Module : This is used on the class that does the work of constructing objects that’ll be eventually provided as dependencies.
@Provides : This is used on the methods inside the Module class that’ll return the object.
@Inject : This is used upon a constructor, field or a method and indicates that dependency has been requested.
@Component : The Module class doesn’t provide the dependency directly to the class that’s requesting it. For this, a Component interface is used that acts as a bridge between @Module and @Inject.
@Singleton : This indicates that only a single instance of the dependency object would be created.
Don’t worry if the above stuff went over your head. We’ll now develop an application that uses Dagger and provides SharedPreferences as the dependency in our Activity.
The first annotation you’ll use is the @Module annotation. The @Module annotation tells Dagger that the AppModule class will provide dependencies for a part of the application. It is normal to have multiple Dagger modules in a project, and it is typical for one of them to provide app-wide dependencies.
Add that capability now by inserting the following code within the body of the AppModule class:
@Module
class AppModule(private val app: Application) {
@Provides
@Singleton
fun provideContext(): Context = app
}
You’ve added a private field to hold a reference to the app object, a constructor to configure app, and a provideContext() method that returns the app object. Notice that there are two more Dagger annotations on that method: @Provides and @Singleton.
@Provides and @Singleton
The @Provides annotation tells Dagger that the method provides a certain type of dependency, in this case, a Context object. When a part of the app requests that Dagger inject a Context, the @Provides annotation tells Dagger where to find it.
Note: The method names for the providers, such as provideContext(), are not important and can be named anything you like. Dagger only looks at the return type. Using provide as a prefix is a common convention.
The @Singleton annotation is not part of the Dagger API. It’s contained inside the javax package you added to your build.gradle at the beginning. It tells Dagger that there should only be a single instance of that dependency. So when generating the code Dagger will handle all the logic for you, and you won’t write all the boilerplate code to check if another instance of the object is already available.
Component
Now that you have a Dagger module that contains a dependency that can be injected, how do you use it?
That requires the use of another Dagger annotation, @Component. As you’ve done for the AppModule, create a new Kotlin file in the dagger package and name it AppComponent.
Add the following code to the file:
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent
You’ve told Dagger that AppComponent is a singleton component interface for the app. The @Component annotation takes a list of modules as an input. You’re using the literal array syntax available in Kotlin, [AppModule::class].
The component is used to connect objects to their dependencies, typically by use of overridden inject() methods. In order to use the component, it must be accessible from the parts of the app that need injection.
-
30Dagger2 Lab WorkVideo lesson
External Links May Contain Affiliate Links read more