#4 Android MVVM Architecture Tutorial - User Login using Retrofit

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hi everyone this is Belal Khan and you are watching Simplified Coding. In the last video we learn how to take inputs using data binding but we just took the input and there is no functionality yet. So in this video we will code the login functionality and that means we will send the email and the password to our back-end server to check whether the given email or password is correct or not now to do this we need web services or you can say RESTful APIs but in this course we are not going to learn about creating web services or RESTful APIs and that is why I have already created the RESTful APIs for this course. So first I will show you the RESTful API that I created and you can use this API in your project as well because I have deployed it in my server. So this is my API and it is taking email and password and when I send a post request to this URL it is returning a json response and that means the login is successful because I entered the correct email and password but if I enter something wrong then in this case I will get this response that means invalid email or password so this is the API that I will use in the project that we created. Now if you want to learn about creating RESTful APIs then you can click here to go to the course that teaches you about creating restful api using PHP and MySQL. Now come back to your Android project and first inside data create a new package and I will name this package network to store all the classes related to our network operation and I will create one more package and I will name it repositories and this packege is to store all the repositories. Now inside network package I will create our Kotlin File/Class and I will name it MyAPI and this is going to be an interface and this is the interface for our retrofit API calls; As you know in retrofit we create an interface and we define all our API calls inside the interface. Now if you want to learn about retrofit in detail then again you can click here to check retrofit tutorial I have a separate retrofit tutorial as well; so you can go through that tutorial as well if you want to learn about retrofit in detail. So inside this interface first I will define a post call so I will write @POST and we need to call login which is the endpoint of my API. So I will write here login now whenever you are using post you need to use @FormURLEncoded in case of retrofit so this annotation is very important, when you are working with @POST. Now I will define a function and I will name it user login now this function will take email which is string and password which is also a string. Now we also need to define the API names because we need to send email and password and these strings should match with @Field annotation values so here we will define @Field and we will write email and the same we will do for password so these names should match with your API calls and you can name your variables anything that you want. Now this function user login will return us a Call and it should be a retrofit call and the type of this call would be a ResponseBody, that means this call will give us a response body. So this is our function that will perform the user login and will return us a call then we will execute that call to get the response, as we are getting here. Now inside this interface I will create a companion object and inside the companion object I will create an operator fun invoke and the benefit of using this invoke is whenever I want to call this invoke i will just write MyAPI and then () and it will call this invoke. It is same as calling MyApi.invoke(). Now this invoke will give us MyApi and to create our API we will use retrofit so here we will write return Retrofit.Builder() and first we will set the base URL and this is our base URL till this mvvm so I will copy it and i will paste it here and I will remove the login so we have the base URL then I will add the converter factory and we need to use GsonConverterFactory.create() then finally we will build the retrofit instance and from the retrofit instance we will get MyApi instance so we will write create, actually we will call the create function from the retrofit to get our API instance. So here inside the create function we need to pass our API interface which is this interface MyApi so here we will pass MyApi::class.java and we have the MyAPi returned by this invoke operator so we have done with our API part but remember we cannot directly call this function from our LoginActivity because our architecture pattern says our LoginActivity will only communicate with ViewModel, so we are sending the email and password to the ViewModel then the ViewModel will interact with the repository to send the email and password to our back-end web server and then web server will check if the email and the password is valid or not and the web server will return the response. So this is how it should be done. So inside our repositories package we will create one more file and it is again a Kotlin File/Class and we are going to create a class and I will name it UserRepository because we need to interact with UserRepository from this AuthViewModel. And our LoginActivity will interact with AuthViewModel and then AuthViewModel will interact with UserRepository, so this is the chain that we always need to follow if we are working with MVVM. Now inside this class UserRepository I will create a function and I will name it user login because this function will perform the actual login and to this function again we need to pass the email and the password which is string and string both email and password are string and this function will return us a LiveData of type string because currently I don't need to or I don't want to parse the response to make the things easy. Now inside this function I will create a val and I will name it loginResponse and it is MutableLiveData because we cannot create an instance of LiveData. It is an abstract class so we will create an instance of MutableLiveData and the type of this LiveData is string. Now inside this LoginResponse we will store the response that we will get from the API Call and to make the API call we need to use this MyApi interface that we already created so what we will do here, we will write MyApi and then parenthesis we need to import MyApi and to import you need to press alt + enter so we have the MyApi here now. From MyApi we will call userLogin() function but the problem is we should not do it like this as we are creating an instance of MyApi inside our UserRepository class and it is making our UserRepository class dependent on MyApi and it s a very bad practice so instead of creating the MyApi instance here we need to inject it and we will learn about this thing when we will go to dependency injection but just for now I am doing like this but keep in mind that this is a bad practice. So we have MyApi then we called userLogin() and to this function we will pass email and password and then to perform the call we need to enqueue() and inside this enqueue() we need to pass a callback interface and you need to use the retrofit callback because you have so many callbacks here but remember you need to use the retrofit callback and this is the retrofit callback and this callback will give us a ResponseBody that's it. Now we need to implement the members and to implement the members put the cursor here press alt+enter and select implement members and we have two members onFailure() and onResponse() so inside onFailure() we will get the failure message from this throwable instance and we will put it inside our loginResponse. So let's do it we will write loginResponse.value equals to t.message that's it. Inside the function onResponse first we will check if and we will check whether this response is a success or not so we will write if response is successful that means we have a success so we will get the body of the response and we will add it inside our login response so we will write here loginResponse.value equals to response.body() and then string(). In case of an error that means when the response is not successful we will get the errorBody() that's it. So we have the API call here and finally we will return the loginResponse because this function is returning a LiveData. Now we will call this function from our AuthViewModel, because you know what our architecture pattern says our activity will communicate with ViewModel and ViewModel will communicate with repository so this is our repository which is communicating with our back-end API so we will call this function from our view model so this is the chain that we need to follow always. So keep this thing in mind. So come back to AuthViewModel and here I will create another loginResponse and I will get the loginResponse from UserRepository parentheses and then userLogin() and here we will pass email and password and as we already checked that the email and password are not null. We can put this operator to make sure it is not null now this userLogin is returning us the loginResponse and it is actually a LiveData that we can observe in our LoginActivity and to do this we will use our authenticationListener. So we will write authListener? and then onSuccess() and we will pass the loginResponse but the problem is this function onSuccess that we have inside our authListener do not contains any parameters so you just need to add a parameter there and to do this very quickly just press alt+enter and select add parameter to function onSuccess() and then select refactor and it will add the LiveData parameter to your function and it will also add the LiveData parameter here where we are overriding the onSuccess() function so we are good to go. So what is happening we are calling our userLogin function that is inside our repository class from our ViewModel class now we have another issue here that we are creating a UserRepository instance inside our AuthViewModel and again this is a bad practice we should not create instances of other classes inside a class because this makes AuthViewModel dependent on UserRepository and it is resulting in tight coupling. So it is a bad practice but just for now we are doing like this, because later we will learn about dependency injection and other stuffs and then we will remove this problem. So for now this is okay. So we are getting the onSuccess inside our LoginActivity and here we can observe the LoginResponse and to do this we just need to write loginResponse which is this parameter dot observe and the first parameter is the owner which is our activity so we can pass this because we are inside an activity now and for the next parameter we will pass observer, now observer will return the value in this it keyword so we can simply toast it. Because for now we will just display the response in the activity with the help of a toast and in coming videos we will perform the actual login operation that means when the user logs in he will go to the HomeActivity. So we will do this in the coming videos, so for now it is okay and one more thing that we can do is we can display a progress bar and to display a progress bar we can use the progress bar that we already created in our design you can see we have a progress bar here so we can use this thing. So come back to your LoginActivity and here we can write progress_bar which is the id of our progress bar dot visibility equals to the View.VISIBLE so when the login task is started or the login function is called we are displaying the progress bar. Now to make it shorter we can also create an extension function to display and hide progress bar so I will do it inside my ViewUtils file that we created in the last video so come inside ViewUtils and here create fun ProgressBar.show(), so this is an extension of ProgressBar and here we will set the visibility to visible. And we do not need to import this. So now the progress bar is visible and the same way we will create one more function to hide the progress bar and this time we will set the view to gone. So we have the functions to show and hide progress bar and now we can use these functions so come inside LoginActivity and here instead of this we will just write progress_bar.show() and we need to import the function that's it. And the same way we will write here progress_bar.hide() and we should write this in case of a failure as well so we are displaying the progress bar when the task is started and when the task is finished we are hiding the progress bar. Now let's try running the application but before running it make sure you add internet permission into your AndroidManifest.xml. So here I will define an internet permission that's it and let's get rid of this warning so press alt+enter and select tools ignore and it will ignore this thing now we can run our application so let's run it. So this is our application, now let's try signing in so I will enter my email and my password and let's try sign in and we are getting the response so it is working fine but we are not able to see the progress bar and the problem is we are hiding the progress bar here so it is displaying the progress bar and it is hiding the progress bar. So the process is very quick that is why we are not able to see the progress bar. So to see the progress bar we need to hide the progress bar when the API call is completed and to do this we will hide the progress bar inside this observer and now it should work, so let's try signing in and you can see we have the progress bar and we have the response if you will enter some wrong password then you will get a different response so it is working absolutely fine. So that's all for this video friends in case you want my source code then you can get it from the link that is given in the description of this video and I hope you found this video helpful and if you actually did then please LIKE this video and SHARE this video with your friends. So thanks for watching everyone this is Belal Khan now Signing Off.
Info
Channel: Simplified Coding
Views: 60,436
Rating: 4.9383259 out of 5
Keywords: android mvvm architecture components, android mvvm with room, android mvvm demo, android mvvm livedata example, mvvm android example, mvvm android theory, android architecture components retrofit, android architecture components tutorial, android mvvm simple example, android mvvm login retrofit
Id: 1GBCg70G7cI
Channel Id: undefined
Length: 19min 11sec (1151 seconds)
Published: Wed Jun 12 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.