The Ultimate Retrofit Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys and welcome back to a new video in this video i will cover everything you need to know about retrofit so we will make a very basic app here that fetches data from an example api um that you can also use of course so when i relaunch the app here then you will see there is a progress bar and when it loads it just shows all the to do entries or whatever that is in recycler view and yeah that is basically fetched from the network i will really do everything here in this video so i will also do the layout part so really the app from scratch if you don't want to see the layout part then you can find jump marks on this video so you can just skip to the coding part and get the layout from my github repository in this video's description so the only real pre-requisites you need here for this tutorial are the dependencies so here i'm just in an empty android studio project and here in the build.gradle file you can see i already pasted the retrofit dependencies and the creatine dependencies and the life cycle scopes for crew teams because we will use croutons here in combination with retrofit to make our requests and get the responses so you can just go to my github repository link in this video's description and copy these dependencies over and also don't forget to enable view binding here because we will use viewbinding here but the rest will be made from scratch so um we will actually get our data here from this website jsonplaceholder.tipicode.com and you can see that has a slash to do's and that is just an example api just to experiment with that you can see that is a json response we get here with ready made example to do items so every to do item has a user id which we won't need here it has a real id that is unique here it has a title which we will show in our recycler view and it has a boolean whether this item is completed or not so just very quick what is retrofit retrofit is just i think the most widespread library for android to make http requests to get this kind of data so if you have some kind of json data and you want to get that into your app then retrofit is the library to use for that because it just works very intuitively and easy and also this tutorial as i said i will do this app from scratch but i will really focus on this retrofit part so i won't go very deep here into recyclerviews and all that stuff but i will still cover it in this course so let's get back to android studio and we want to start to make our layout so we switch to our arrest folder layout activity main xml so everything will happen here in this main activity where we just have an hello world text view which we don't need we can click this and remove it and then we want to switch to the code tab i will open this tag here and in here we will have two views on the one hand we will have a recycler view of course match parent match parent this will just fill our whole screen we can give it an id of rv to do's because it's a recycler view that displays to-do's and we can close this stack and we will have a progress bar that just that will just display when the request is made and will be made invisible when we get the results this will have wrap content and wrap content give it an id of progress bar and that is actually it now we need to set the constraints for these two views let's go back to the design tab click on the recycler view and constrain it horizontally and vertically in parent and let's do the same for our progress bar horizontally and vertically in parent and we should of course set the visibility of this progress bar to gone by default so back in our code tab we set the visibility to gone and that's it for our main activity we also need another layout which is um the layout for our to-do items so there we just have a text view in a checkbox so let's go to our layer folder new allow resource file and i'll call it item to do press enter we will directly switch to the code tab and here we will first of all have a text view that is place the traduce title um layout with let's set it to web content for now we will change this later hide as well give it an id of tv title i will give it a little bit of a margin start let's say 16dp i will set the text size to 20sp and i will set tools colon here we need to press alt plus enter to create this namespace declaration um we will set the text of that to placeholder but because we prepended tools here this will only be applied to the layout editor and not to the text view in our app then we can close this tag off then we also want to create a check box whether the studio item is done or not wrap content web content give it an id of cb done for checkbox done and that is actually already it for that checkbox now we only need to set the constraints for those two views let's switch back to the design tab um actually no let's switch back to the code tab we also want to set the height of our constraint layout to 75 not 85 75 dp um it's always hard to see my keyboard here because of my mic but um let's now switch to the design tab you can see now we have an item with a height of 75 tp and we want to take our placeholder constrain the left to the parent left then we constrain it vertically in parent then we take our checkbox constrain the right to the parent right and also vertically in parent then we want to take our placeholder again constrain the right to this checkboxes left we don't want to have this centered instead we want to fill the whole width so basically from here to here so what we need to do is we need to set the layout width of that textview to 0dp so back in our code tab change this to 0dp and it removed the margin let's reset that margin start 16dp and then yes now it looks exactly as i want it okay let's now get to the retrofit part which is actually more exciting which is why you watched this video um first of all we need internet permission for retrofit so let's switch to our manifests folder and make sure that we don't forget this this is a very common cause of crashes here uses permission and internet whoops i want it like this and that's already it for the manifest now how do we actually tell retrofit how we want to access our api so our api is in the end just what i showed you here in chrome which is a remote service that provides some data for us or that we can also use to post data well i will only show you how to get data but posting data or updating data is basically the same with retrofit for that we need to define an interface so we go back to android studio and create a new class kotlin class of file and it's actually another class but an interface here and we will call this to do [Music] api so in this interface we now define all the functions we need to access our api so in our case that is just a single function to just get all these to do items but in a real project you usually have much more of these functions you might have a function to post a new to do to update it to do or to delete it to do that is remotely saved or whatever but just for demonstration i will show you how we can retrieve all of those to do's from that api so we define a function here we call that get to do's and what will that return with retrofit we want to return a response you can see that is a response that takes a generic argument so it's always a response of a specific type and well of what type is our response that we get here if we now take a look back in chrome then well we get a json response here so of course json is just a way of communicating that everybody rather every language can potentially understand or parse to something the language really understands so what we essentially need is a network model class so we needed we need a class that represents such such a to do item here so a class a data class that has a user id a normal id a title and a completed boolean and you of course could now just create a data class and give it exactly these attributes that would work here those are not many attributes but often in practice you have much more of these attributes and then it would be very tedious to create these data classes by hand to solve this problem in an easier way and more comfortable way we can simply copy this json response of a single to-do item and then use a fancy plugin here in android studio which is called here kotlin data class file from json so in case you don't have that plugin you can press ctrl alt and s to open your settings and then i'm going to scroll down to plugins you want to go to marketplace and search for json to cut in class so that is the plugin you want to install here i already have it installed but when you have that and restart android studio probably then this option will occur for you you click on that and you can simply paste that json response that you get from your api and this plugin will now generate the data class for you so you can see down here we need to give this data class that will be generated a name which i will just give to do because that is a to-do item then we click on generate and you can see here a new class popped up if we open that here's our data class to do complete boolean id title and user id and also the types are correct so now we have a kotlin class in which we can parse the json response we get from our api so you might think now okay that will be a response of type to do but that's not correct because we get multiple to do's so what we essentially want to have we have a list of to-do's you can also see that here in chrome though those square brackets um always mark that we have a list of something in json and these curly brackets just make this a specific object so in our case a to do item okay but now that is just a standalone interface and it doesn't have much to do with retrofit with someone need to tell retrofit how we want to retrieve those to-do's here and when we're talking about http requests there are four main types of requests on the one hand get requests post requests um put requests and delete requests get requests well are just used to retrieve some data to get some data that is what we will use here post requests are used if you want to post some data from your device to the remote server put requests are used to update data on the server and delete requests well to delete data but since we want to retrieve data here we will use a get request and then we need to annotate that with add get and here in the parentheses we need to specify a string so the string that we need to put in these parentheses here can be found if we take a look at our api that is whatever comes after our base url so the base url is everything until dot com so this part here is the base url and this is the specific url of that whole url we want to actually get something from so we will specify the base url later but we are interested in this slash to do's now so we go back and write slash to lose and now with this function is the case that we don't have any query parameters so we don't pass any parameters to this function um usually that's the case or very often for example if you want to if an api takes an api key so you somehow need to authorize that you are allowed to access that api then you need to pass that apa key to each request so then you would need to write at query here to make that a query parameter here you specify the name of the query parameter that the api accepts so maybe api key or just key that is very individual from api to api and you will have to read the api documentation to find that out and then you can give this a name and a type so that is how you can essentially attach query parameters to your requests um that is not what we want to do here we don't need an api key or any other parameter but that is still something of retrofit you need to know how that works so i still want to show you that i also want to show you another functionality of retrofit which we don't need here but which is important to know and that is if you actually want to post some json data to a server so let's say we have a post request here function post to do or create to do so you created to do in your app and you want to post that to the server then this will also answer with a response here probably not with a list of to do's let's say that is a great to do response we don't have that class now but just that this looks a little more realistic and then this would be a post request so you can see for each type of request we have an annotation here and let's say that is create to do and now how would you attach the to do that you have to this function so it actually gets posted to the server this time you can't do that as a query parameter query parameters are just these parameters that you have in the url if you want to attach json you need to make that a body parameter so you want to attach a json body and here you would pass the to do that and this would automatically get parsed to json if you have this body annotation and then the server will just worry about this to do that you post to it so just that you have seen this because that is a crucial part of it retrofit that you need often but it's not always that easy to show that with an example api you would need a real api for that and i actually did that in my new set playlist so make sure to check out that if you want to see how you can apply that in a real project let's get back to our app here actually this is almost everything for our to do api interface one more thing that's missing is well we want to execute our request in a crew team so requests network requests should always happen asynchronously never on the main thread so what we want to do here is we want to prepend the suspend keyword and that will automatically execute that in a crew team okay now we have that interface but we also somehow want to create an instance of that interface and for that we need to create our custom retrofit object that will create this real api for us so we can use this function to make actual requests for that we will go to a root package create a new carton follow class and call that retrofit retrofit instance select object here because that's a singleton and in here we will create our api if you use dependency injection with dagger hilt or so then you don't need this then you instead create this api interface in your specific module and provide it but we don't have that here so we will have a val api here which is of type to do api and we initialize this by lazy that just means it won't be initialized right away instead it will be initialized when we first access this api so in here we can use retrofit dot builder and then construct our api so you can see we have a bunch of functions we could call here on one hand we need to pass our base url which i explained before that is just https um colon slash slash jsonplaceholder.tpcodes.com so that is everything which does not belong to this part after the base url basically so that is just the url that we want to access to get or to do and that is the ul that we always access with our requests so i hope that gets clear then we can also add a converter factory that will be a gsmconverterfactory.create what does that mean well we somehow need to retrofit someone needs to know how it should take the json data it gets and how it should parse that to these data classes that we created here and for that we will use json which is just a converter for json we could optionally also add a converter factory here that will be useful if you want to parse the response to something for example if you want to get that as rx java stream but we also don't have that here so we can leave that empty so then we can just call build to build our api or rather that retrofit instance that's not the api yet for that we need to create and specify the class of our api and then the errors are gone and we can use this instance here to make our api calls and now that we that we have our api to make our request to fill our recycler view we of course need to create the resector view adapter next so new cut and filler class to do adapter select class which we'll inhabit from recyclerview.adapter and here we create an inner class for the viewholder like this and then we will have that here in a class to do view holder since we use view binding we need to pass the binding here instead of view so binding of type item to do binding if you don't have that make sure to have this viewbinding true included here in your built-it gradle file then we let that inherit from view holder here we need to pass a view which is just binding that root then i will just use a basic list differ here so in case you don't know what div util is that's just a tool basically that um makes it very efficient to update recycler views i won't go very deep into this here you can watch my project playlists where i explain this in more detail so for that we just need a div callback which is of type object um diffutil dot item callback here we always compare two to do items so we just need to define how we want to compare our items how diffutil will decide if it should update an item or not and here we'll have two functions our items the same and our contents the same which will override for our items the same we can just return old item.id is equal to new item.id and for our contents the same we return old item is equal to new item we can create a private valve for our actual list differ so differ it's equal to an async list differ so that will that updating process will happen behind the scenes basically on a background thread we need to pass our adapter which is just this and our difficulty back then we will have a variable for our to do's list so that is a list of to do i'm going to overwrite the getter for that which is differ.currentlist and the setter which is or whether in which we want to submit a new list so differ submit list value and i know i went quicker through this because as i said the focus is not on the view to in this video it is on retrofit so then let's just override the three functions we need for each recycler view on the one hand get item count which is the easiest function that will just return the list of our the size of our list and then we have on create view holder here we need to return an instance of our viewholder to the viewholder um we need to pass a binding so item to do binding that inflate for that we need to pass a layout inflator.from we can get the context from our parent then we need to pass the parent itself and we don't want to attach this to the root layout and finally for onbindviewholder in which we just set the data to our views in our recyclerview we will use our viewfolder a dot um actually i think yes this binding must be a valve so we can access it so now we can call holder dot binding that apply get the current to do item by writing that to do is equal to our to-do's list at the index of position and then we set tv title dot text to to do dot title and cb done so our check box that is checked to to do that completed now that's it for our recyclerview adapter and the rest will basically happen on our main activity if you use mvvm architecture which i suggest you to do in a real app then you would make the retrofit call in the repository and then call that from the viewmodel but that would be too much here so i will just do it from here on the one hand we of course again need an instance to our binding instance private latent var binding is activity main binding this time initialize this year dot inflate and pass our layout inflator and then we swap this out with binding dot root like this then we want to create an instance of our recyclerview adapter to do adapter of type to do adapter nothing special we create a private function to initialize that recyclerview and just set it up set up recycleview set equal to binding dot retroduce that apply first we set the to-do adapter to a new to-do adapter then we set the adapter of our recyclerview to this to-do adapter not this to do adapter then we set the layout manager of this recyclerview just to a linear layout manager and pass this at main activity because just this would refer to this recyclerview here so this apply block then we can simply call that function here oncreate and now finally make our api request so as i said we want to execute that api request on a background thread so we want to launch a curtin here lifecycle scope dot launch when created which is just a curating scope that is life cycle aware so this curtin will be cancelled when the app goes in the background and in here we first now want to set our progress bar visibility to true because now we start to make our api request and as long as we make that our progress bar should be visible and then we can get our response in the try and catch block so if we use retrofit with curtins then we can catch errors by simply doing that request in the try and catch block so here we simply use our retrofit instance our singleton our api and here when we first access it it will be initialized and get to those and we want to catch two types of exceptions here on the one hand an io exception and on the other hand an http http exception so what is the difference between between these two exceptions io exception is well most likely that you don't have internet connection but it can be multiple it can have multiple reasons so you definitely need an additional alternate check here in a real app but just that you know that there are two types of exceptions it could also be that the output stream is closed or whatever so i just want to have a log statement here an error log we need to create tag here console.tag is the main activity and here we just write io exception you might not have internet connection we can copy this paste it here and replace this with http exception which usually happens if you get an unexpected response that doesn't start with a two so if you have http responses those are just a three-digit code and if this three-digit code does not start with the two then this http exception will be thrown so that usually means unexpected response and in both these cases we want to return out of launch when created so if this code continues until here we know for sure that we got a response back but that does not yet mean that the response was successful um we still need to check that so if the response is successful so that just means that it returned the http ok status code and if the response dot body you can see that now returns a list of to do items if that is not equal to null then we know that we really got to use and then we can use our to-do adapter dot to do's and assign our response dot body to this so we now set our to do's list to our adapter and here we need to assert that it's not equal to null um but at this point it will never be now here in our case and else we want to not paste that one i'm going to paste an error log again that just says response not successful and finally call binding dot progress bar and set the visibility to false again because either way if it was successful or not we want to hide the progress bar again and by the way we should also use this and put it here in the catch blocks because if we return out of those we also want to hide the progress bar before and that is really it i know this is this seems to be a lot to make a simple http request but but usually you need to make multiple different http requests and it's actually very easy to add more now it's just the initial setup that requires a little bit of work here so if you have more types of requests then you just go into your api interface and add more functions and that's it then you can access those um but yeah essentially as a quick little recap you need an api interface to define how you want to access your api in which ways here and then you can use that api interface to simply create that api with a retrofit builder and then you can use that api um as you can see here to execute the functions you defined in that interface and that will make the actual request so let's quickly launch our app and see if everything is working but it should it loads and there are our entries our to-do's we could check those but this doesn't do anything here it's just important that these that are checked by default are also checked here the titles all match and yeah just a bunch of to do items here and you have successfully made maybe your first http request in android if you don't just want to make such a basic app that needs to make http requests then you can on the one hand watch my new sub tutorial as i said where we'll just make a basic news app but if you are looking to build your very own api so that you can decide which data is returned here and then check out my website you'll where we'll find a cater course so cater is essentially just a back-end framework that is completely based on kotlin and curitins and with that i show you in this course how you can build your api use retrofit to retrieve that so you will learn how to make a note app that just creates notes and those notes will be synchronized with a remote server so these will be saved online in your very on your very own server and yeah if you just want to learn that that'll pay course that is a way you can support me and my work but of course also to dive deeper into android and back-end development so if you're interested check out the first link in this video's description which will lead you to my website and there you will find my premium courses with the code fill up 15 you will get 15 off by the way of all these courses so that's it for self promo i wish you an awesome day i hope you liked this video if so tell me that below in the comments and see in the next video bye bye [Music] [Music] so you
Info
Channel: Philipp Lackner
Views: 11,772
Rating: 4.9501781 out of 5
Keywords: android, tutorial, philip, philipp, filipp, filip, fillip, fillipp, phillipp, phillip, lackener, leckener, leckner, lackner, kotlin, mobile, networking, retrofit, http, http request, api, rest api, android studio
Id: t6Sql3WMAnk
Channel Id: undefined
Length: 34min 48sec (2088 seconds)
Published: Wed Jan 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.