Everything You Need To Know About Retrofit in Android | Get Data from an API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up youtube this is dennis ponyta for tutorials.eu in this video you are going to learn how to use retrofit in android in order to get data from an api so load data from the rick and morty api in this particular case and then display it in a recycler view and we're going to build it up step by step and then in the next video which will come next week we're going to look at mvvm so model view view model and then in the third video we're going to look at co routines okay so we're going to use that particular example and we're going to build up on it so first we're going to build it in a simple and dirty fashion but using retrofit in order to load the data in the second video we're going to clean it up using mvvm so that we are using this pattern and have a proper architecture and then in the third video we're going to look at co routines in order to optimize our code even further and well you are going to require co routines in the future whenever you want to do stuff in the background which means run something that is not going to run on the main thread if it's not required so let's start with this particular example looking at retrofit and building this little application and if you think that this is a great idea and you are excited about this video then hit that like button it really helps us out and also hit the subscribe button if you haven't subscribed already and now let's get started [Music] all right so before we build the application let's look at the android networking with retrofit overview where you will get an idea of how networking so basically connecting to an api with retrofit works so there are two different parts to consider when making a request the client and the server so a client can be any of your devices the phone the tablet the laptop or even a browser while the server can be any central computer or program that controls or provides the information that you need so you're sending the request to the server and the server gives you a response which then can be used on the client side in order to display something so to display the data so it's our task as developers to then use this data and present it in a nice format so the client and server uses the http method to communicate with each other that is the hyper text transfer protocol so if you were wondering what http stands for and there are specific methods created to enable them understand each other which include the add get and that's the get method that tells the server that you need to read data from it then add post which is the post method that tells the server that you need to create or add data to it then you have the put method which tells the server that you need to update an already existing piece of data and then you have the delete method that tells the server that you need to delete specific data from it so it's actually a create read update and delete process so in our case we're going to send a request to a page and then it will load all of the data and it will give us back the data in a certain format in form of a response and we are going to try then to build the application that you can see on the left hand side so that the client meaning our phone will display this so there are five different ranges when it comes to the response status code you have the 100 to 199 which is information then you have the 200 range which is success you have the 300 range which is redirection 400 which means that there is an error on the client side and 500 which means there is an error on the server side so the 500 range so to speak but the most frequently encountered ones are 200 which means that your request was successful 404 which most people might have experienced which means the information you requested was not found so the client might have to send a request that does not exist or is an incorrect one and then the 500 which is an internal server error or 503 which means service is unavailable so here's the api that we are going to work with so rick and morty api dot com slash api slash character slash and then the request that we do we want to display page one okay let's look at the sample json response so here you see if you enter this link and you look at the raw data that you get this is what you're going to get so there are results which is going to be an array and this array consists of for example the id1 which contains rick sanchez as the details and that's the one that we are interested in so we're not going to care about the id the status the species the type and so forth we are only going to take the name as well as the image that you can see highlighted here and the image is basically just an url that you can then use in order to then display it on your phone and in your application all right so here would be a shorter version of the data that we are going to need so we will create a character response class to represent the first curly brace with a list of results the square bracket represents an array or a list and then we're going to create a character class to represent the curly bracket inside of the array which means in this case it's the name with rick sanchez and then the image with the well url to the image of rick sanchez all right so let's go over to android studio and actually build the application so you're learning something about android app development in this video and maybe you want to learn a lot more about it then you can check out one of my two courses so if you are a beginner android developer then i would highly recommend to check out my android master class course there you will learn to build android apps from scratch and you become a real android developer or maybe you want to become a better android developer because you are one already and you want to become a real pro then i would recommend to check out the jetpack master class because there you will learn how to use jetpack which is a suite of frameworks that will make sure that you are a senior app developer all right so i would really recommend to check out those courses if you want to step up your app development skills very quickly you can find a link in the description below which will send you to the course with a huge discount all right so thanks a lot for checking out those courses this really helps us out and this enables us to create these videos either way i wish you a nice journey to becoming a great app developer and now let's get back to the video alright so now in android studio let's go ahead and create a new project i'm going to select the empty activity here i'm going to call this application retro fit example and the package name is going to be in my case eu dot tutorials dot retrofit example then as the minimum sdk i'm going to use android lollipop so api 21 which runs on pretty much all devices and that's going to be fine so let's click finish and create this project okay once this project is created let's go over to our build.grail retrofit example app file and here we are going to need a couple of things so the first thing that i want to make sure that i have is going to be my is going to be that the view binding is enabled so here inside of android at the very bottom i'm going to add the lines build features and view binding set to true so this will now allow me to enable view binding and use it in my application and now down in dependencies where there are already a bunch of dependencies for example the app combat the kotlin extensions the materials and so forth that's where i'm going to add my own dependencies that i want to use which will be retrofit and moshi so first of all let's add the versions and i'm going to use the moshi version of 1.9.3 and the retrofit version of 2.9.0 okay and then in order to use retrofit i'm just going to add this implementation here saying com the square up retrofit two colon retrofit colon and then the retrofit version that we had here with a dollar sign so here you have to be super precise otherwise this won't work and retrofit is going to take care of the networking side so it will allow us to download data using a get request for example and then we're going to use moji moshi will help us to convert a json file into something easily readable which will be kotlin objects it will basically convert json data into kotlin objects that we can then very easily use and then i'm going to use the retrofit with moshi implementation which will allow me to convert retrofit into moshi which will then do the trick to convert it into our required kotlin objects and then i will use coil so here this will allow me to load the url and then directly use the image inside of my application so in the image views this will allow me to be a lot faster with it a lot less code instead of doing it the old-fashioned way so now let's sync it and let's wait for the syncing to be done and now that it's done i'm going to go ahead and make sure that i have internet permission in my android manifest because that's something that you might forget and it's really important to make sure that you have it because otherwise well this whole thing won't work so you need to ask for the permission to have access to the internet inside of the android manifest with this line here otherwise you won't get internet permission all right so now that that's done let's go ahead and inside of our tutorials you retrofit example let's create a new folder so i'm going to create a new package here and i'm going to call this one network and inside of network that's where i'm going to put my networking information so first of all let's go ahead and create a new kotlin class that will be my character okay so i will have my character which will be a kotlin class like so so this will be my data class that i want to create all right and this data class will take care of the model so this will basically be my model class all right so let's add the data keyword in front of it and then also let's make sure that we're not using the curly brackets but we're using rounded brackets like so so the data that i want to have here will also use json so basically we want to use the json details which means the name for example which will be crazy rig which we for example get from here okay this is insanely unreadable so there is this json formatter you can use any json formatter which will help you so i'm going to use this json name property and i want it to be the property in my data class so it will be rick j sanchez and then i want to use the image in order to well get this url and then display it okay so this is just a formatted version which is a little more readable and now you could read a lot more information from it as i said earlier and you could use it so you could even display whether the character displayed as human male and so forth okay so now this data class should use all of that how can we make sure of that well we can go ahead and just use the first of all json so import com dot square up dot mushy dot json like so all right so this of course will only work if you made sure to add mushy here otherwise it wouldn't work so now what is our character going to consist of well first of all he will have a name which will be of type string and then he will have an image which will be of type string as well because we just get the url right so this by itself would work fine but i want to specifically say that this will be the json object that has the name of name okay and then the same goes for this image i will specifically state that this will have the name of image okay so this is not really necessary in this case because we are using the exact names already but this is just good practice if you want to make sure that this is actually going to work perfectly so add this and then what it will do is it will basically link this property this name property to the data that we get from here which will be linked to this name property of json okay so the same goes of course for the image as well so here this image here all right so that's what this data class is going to do and in here i'm also going to directly create another data class which will be the character response so this will give us the name results so the json results and i'm going to make sure to have a result here which will be a list of my character like so and this needs to be close to this opening bracket so here we're just saying okay we want to get the result which will basically be a list of the character data objects that we had up here so if you look at the result you see here that there are results okay so we get multiple results and each of them is going to be a character so the first one is rich sunchase second one is morty smith then summersmith beth smith and so forth so this is a list of characters that we get and the results so the result that we are interested in is going to have this information for us so that's basically what we're saying give us the results and make a list out of it and what kind of list well a character list all right and next inside of my network i'm going to create a new interface so inside of the network folder let's create an object class so here kotlin class file select object down here and call it api client so this will be our api client using the object keywords so we can call the api service directly without needing to initialize the class so we don't need to create an object of this class in order to use it so what is it that we want to do here well first of all we need to get the url the base url that we want to modify okay so let's create a variable that will be this base url so private value based url which will be this string of https colon forward slash forwards thresh rick and morty api.com api slash and then whatever comes after is modifiable because if you go to the api of rick and morty you can select multiple different api calls so here you can get the characters so go over to docs you can get the characters you can get the locations the episodes and so forth right and we are interested in the characters so here get all characters get a single character got multiple characters there are different kind of options here so we're going to get the characters which means we will need to use character as the next part and then another slash and then comes the page at which the character will be okay so this will be the base url that we're using and next we need to create a variable for the moshi builder okay so we're going to use that in order to convert the url into something that is usable so here let's use moshi and in order to use moshi we need to make sure that we have the imports okay so first of all let's add the kotlin json adapter factory and then also the moshi namespace so here you see the two imports are added to the kotlin json adapter factory as well as moshi and now let's use retrofit so we create an instance of retrofit using the by lazy keywords here this will allow us to initialize only when it's needed and pass the base url and the mushy variables created above so for this to work of course we need to make sure to import retro fit so let's import that and the moshi converter with alt enter okay so what we're saying here is build something with retrofit use the base url then add the converter factory using our mushy converter factory which creates using our mochi and then we build it so basically this will create the url which will then be used in order to get the data from the api so now below this object class let's go ahead and create an interface and it will be the api service interface so what this will do is let me first of all make sure that i get the imports right here so import the get keyword query as well as retrofit call and here we're going to use the retrofit 2 call okay so let's look at the imports you see we imported a bunch of retrofit libraries so here the call the retrofit the moshi converter factory http get as well as query so what's up here so we create this get which will get us the character and we're going to have a function here which will fetch the characters with an query so a search so to speak where we are querying the page and we call to get the character response and what we want to get are the characters all right now that we have the api service ready let's go ahead and create an instance of the api service inside of our object api client here okay so i'm going to create that at the very bottom where i'm going to basically say api servers is going to be loaded lazily and we're going to use this retrofit that we just created in order to create an api service so what this will just allow us to do is to actually use this api service to then get the characters so now in our main activity that's where we can go ahead and actually use it so let's first of all create a variable and call the fetch characters method so here we create a new client where we use our api client dot api service so this is this api service that we just created this instance of our api service so that we can now use it and we call the fetch characters method from page one okay so that's what's going to happen here because we're saying basically add to the url the page and then use page one so that's what's happening here and then let's call the enqueue method and pass the callback interface and then overwrite the unresponse and failure so now let's call the enqueue method and pass the callback interface and then overwrite the on response and on failure so what that means is we're going to use this client here to then enqueue our callback so here we're creating our callback with our character response okay and then we and then we have to add the different statements in here so now this callback will require you to add the own response all right so here when we get the response what is it that we want to do well we want to first of all check if the response is positive so here we say response is successful so if the response is successful then let's execute some code here okay what is it that we want to execute well for now let's just display the response body okay so let's get the entire response body onto our console and then and then we also need to check what should happen if this was not successful so here so here let's add the on failure as well so on failure we are going to get the failed message and in case it is complaining here for you what you can add is enterfit2.callback so we are using the retrofit2.callback maybe i had the wrong import here as it seems it used this java x security off callback so if that happens just make sure that you are using the retrofit to callback okay so this will just be a callback that will basically run this api service it will fetch the page and then if it was successful it will give us the page as the response start body so we are reading the entire page so to speak and on failure we're just going to lock the error so now if you run the application you will see that it just says hello world and if you look at the logcat and search for character here you will find characters so it's this statement here with the character response and the character response says the first character is rick sanchez with this image then the next character is morty smith with this image url and so forth so we now have all of these beautiful people from rick and morty from this tv show and we can directly use those okay so now we just need to bring them into a format that is a little nicer therefore i'm just going to create an adapter and a recycler view here that will help me with that so what i'm going to use is my recyclerview for that so if you don't know how recyclerviews work i would recommend you check out my video on recyclerviews so here in layouts we will need to create a new resource layout file i'm going to call this one rv item and this will be not a constraint layout but it will be a card view okay so i'm going to use the card view root element and that will be my file so at this point it's not very happy so i'm just going to paste in my code and quickly go over it so basically we have a card view inside of which we have a constraint layout and that's it so inside of this constraint layout which wraps the content is gravitated towards the center and matches the parent we have an image view which has a scale type of center crop we need to have an id for it so we can access it as a source i'm using the default ic image launcher it's to the top of the parent as well to the start of the parent and it wraps its content and then we have a text view which is going to have a text size of 14 it's going to be black it's going to be to at the bottom of the id of the image which means of the bottom of this image view and basically the start to start off will be the image and the end of end off will be the image so let's look at the design we can see that this will basically be the design where you have the image view and the title underneath so image and name so now that will be the individual item the recyclerview item okay and now let's use this recyclerview item in our recyclerview which means we will need to have an adapter so let's go ahead and create a new adapter so here let's go ahead and create a new kotlin class i'm going to call this one main adapter so you're learning something about android app development in this video and maybe you want to learn a lot more about it then you can check out one of my two courses so if you are a beginner android developer then i would highly recommend to check out my android master class course there you will learn to build android apps from scratch and you become a real android developer or maybe you want to become a better android developer because you are one already and you want to become a real pro then i would recommend to check out the jetpack master class because there you will learn how to use jetpack which is a suite of frameworks that will make sure that you are a senior app developer all right so i would really recommend to check out those courses if you want to step up your app development skills very quickly you can find a link in the description below which will send you to the course with a huge discount alright so thanks a lot for checking out those courses this really helps us out and this enables us to create these videos either way i wish you a nice journey to becoming a great app developer and now let's get back to the video now in order to use this main adapter i need to make sure that my activity main is going to be ready to display a recyclerview so here i'm just going to use a default recycle view which will take the entire available space okay so i'm going to call this recyclerview characters recyclerview or characters rv it's going to match the parent in width and height and it's going to be to the well the bottom is going to be to the bottom of the parent and the top is going to be to the top of the part which basically means it will take the entire available space as you see here and it's going to display one item after the other all right now let's go over to our main adapter because this is where a lot of things happen but as i said i would recommend that you check out my video on recyclerviews so this main adapter is going to use the characters list which will be a list of our character class which we created earlier so it's this one here the character class so it should display those and i'm just going to say that it's going to use the recycler view dot adapter class so it's going to inherit from it okay and here we're going to use the main adapter dot main view holder which we of course also have to set up for this to work properly okay so let me get rid of this as well so it says not happy i need to have a main view holder okay so let's create an inner class in here which will be the main view holder and i'm going to just create it like so so this is a generally how a main view holder is going to look like so you need to pass in an item view and then you need to bind the data okay so here i'm going to create a function which will bind the data where i'm going to bind the character well past character and then inside of it i need to assign the name which will take the item view that is passed to me find its id and use its name which basically means it's going to use this recyclerview item name here so the id name this one and then we're assigning the image as well so let's do the same thing with image view so here i'm going to find the view by id using the image view then let me say that the name the text property will actually be the character name so the character that we are loading from via retrofit is going to be now used in order to display it in our recycler view right here for every single item that we're looking at that's what this adapter is for right it's going to fill every single item for us now with the image it's a little more complicated because we're going to load it and we're going to load the character image and we're going to do it using coil so we added this dependency in the gradle you might recall that quite early in the video we added this dependency and now let's go ahead and use it so let's load the image therefore let's make sure we import coil you see coil.load is imported and now we just need to make sure how we want the image to look like so i'm going to say i want it to be in a circle format so circle crop transformation is what i'm going to add here so now this is of course not everything that the main adapter needs so you can hover over it and implement the members that it requires i'm just going to implement all of them so let's do that we have the uncreate view holder on bind viewholder and get item count now let's take care of those so the item count is going to be the easiest one let's start with that one so we're going to just return the characters list size and what is the characters list well it's this one here that we get when we create the main adapter all right and then in the on view holder on bind view holder here we're just going to say the holder should bind the data based on the characters list at the position that it currently is looking at so here the onbindviewholder is going to give us the position inside of the list that we're currently looking at and we're just going to say okay get the characters list at that position and bind the data to the holder so basically basically to that particular item that we're looking at and on create view holder well here we're just going to return the main view holder with the layout inflator using the parent context and we're going to inflate it with our layout that we prepared so r dot layout our rv underscore item so this recycler view item thingy so we're basically saying every single item should look like this okay so that's what this inflate will do for us and as the attach root i'm going to say it's false and then i forgot to also add the parent here like so so this should now inflate the rv item for every single one of the items okay so now let's just use this main adapter that we created because we're never using it and where do we want to use it well if the response was successful okay so in here instead of just using the character response inside of our lock cat let's actually use it and inflate our or fill up our recycle view with it so here let's get the result so vol result which will be based on the response body and i'm going to get the result from the body okay so the response body this one that we used here we're going to get its result and now we can use that result so if it exists then let's do something with it so if it's not empty we're saying do something and here first of all we need to create an adapter object which will be our main adapter to which we pass the result so here as you might recall the main adapter needs to have a characters list and the result that we have gotten if you recall that in the log was in fact a characters list so here characters with the character's response so here it was a result with you see the square bracket that's indicating that this is a list so we're getting character 1 then character 2 and so forth so that's exactly the format that we wanted right so we're passing this to the adapter and now we just need to make sure that we also use our recycler view and we're going to find it by using the id well will be of type recyclerview r dot id dot characters rv which means we're going to use this in our activity main this recycler view and we're saying okay use this recycler view now please and now we just need to link them together so let's use our recyclerview which can be null and use the layout manager which i'm going to use a staggered grid layout manager so that the images can be next to each other right so i'm just going to say to you with the staggered layout manager being vertically aligned okay so that's number one and now let me also make sure to set the adapter of the recyclerview so dot adapter will be the adapter that we prepared okay so that should be it let's see if this is going to work out and if the data is going to be loaded properly so there we are we have rick with morty summer beth and so forth so we have this list and you also see that it's a lazy load so it loads them lazily only once it will be relevant okay all right so this is pretty much it now you've seen how to use retrofit in order to load data and the cool thing is we got this super complex data if you recall here with all of these details so we get the results which is an array of or a list of the different characters right and there is so much extra information but we don't care we only take the name and we only take the image so now if you want to get better at this i would recommend that you also adjust the recyclerview item so that it displays the species the gender potentially maybe even the origin and then you make sure to also add that in here and then adjust your um here the character details what was it further up here this character adjust the data class so that you get this extra information and use this extra information and then display it accordingly and that's a cool thing really with retrofit and moshi that it can be done rather quickly and easily congratulations you made it all the way to the end it was a rather long video but now you know how to use retrofit in order to use an api and load data from it in order to then display it in your application in our case we're using an recyclerview here to display the data so this was just part one of this three-parter and the second part will be mvvm as i stated at the very beginning of the video so definitely don't miss it out and if you haven't subscribed yet now is a good time and also hit that notification bell because well then you will be notified once this video comes out and you can learn how to use mvvm so model view view model which is a very important architecture that every advanced android developer should know alright so thanks a lot again for watching this video and see you in the next one [Music]
Info
Channel: tutorialsEU - Android
Views: 713
Rating: undefined out of 5
Keywords: android retrofit tutorial, android retrofit tutorial for beginners, retrofit android tutorial, retrofit, retrofit android, retrofit android example, retrofit get request, android retrofit, android retrofit 2 tutorial, retrofit android example tutorial, retrofit 2.0 android tutorial, retrofit tutorial, retrofit 2 android tutorial, android get request, retrofit tutorial android, retrofit lesson, kotlin, retrofit android example code, denis panjuta kotlin, android tutorial
Id: s1jqC70uO7Q
Channel Id: undefined
Length: 38min 35sec (2315 seconds)
Published: Thu Sep 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.