Retrofit Tutorial Part 1 - SIMPLE GET REQUEST - Android Studio Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to coding and flow in this tutorial we will learn how to use retrofit which is a very popular Android and Java library that makes it pretty easy to send and retrieve data from a web service it provides an abstraction layer over HTTP cards and automatically generates all the complicated low-level networking code files we simply have to create a Java interface that contains method declarations for the different network operations that we want to do on the server add some annotations to these methods and retrofit then generates the actual implementation for them if some of these terms sound confusing to you oh don't worry retrofit is actually pretty easy to use and the tutorial will be understandable without any pre knowledge about networking on Android and you also don't have to know about HTTP servers and all that stuff basic Java and Android knowledge should be enough to follow along we will start with a simple get request which basically just means that we retrieve data from a server and display it in our app and then we will step-by-step explore more retrofit features in the upcoming paths like how we can send data to a server we will not create a real I prefer lot of features in this tutorial and we will also not care about proper app architecture here because this is just about the retrofit functionality itself but in the future I will also release tutorials will be implemented will fit in more realistic examples and combine it with other concepts and libraries particularly with the Android architecture components if you follow this tutorial then you should also watch the architecture components tutorial because in most real apps nowadays you will be using both and there are a lot of similarities between the room persistence library that we used there and retrofit room is basically two SQLite what retrofit is to web services when you click on the little I in the top right corner of this video you can find a link to the nth word architecture components tutorial ok and as usual I will put a link to the code for each part in the description box under each video and there I will also put links to two websites the first one is the retrofit github page where you can find some simple instructions and when we scroll down under download we can find the dependency which we later have to add to our app and if we scroll up a bit we get to something called converters and these are the libraries that are responsible to the response we get from the zubur into java objects and vice-versa we can choose between different ones and Buber us json so we need this dependency here as well and the second website where beer JSON placeholder dots type a code calm which is a fake online rest api that we can use for testing purposes and rest api in a nutshell means that this is a web service that uses HTTP to communicate between a client and the server this is not the whole definition of rest but you don't have to go into the details here but you can also use a different REST API for example and there are thousands of different ones available online and major sites like github Twitter Facebook and so on also have REST API s if you want to get the most out of this tutorial I would encourage you to choose a different REST API and build your own example because then you will learn much better than just typing the same code as I do but if you want you can choose this one and here when we scroll down we get two routes which are these different URLs that represent the different endpoints of this API so this is where we can get data from and make changes to the data in the first video we will use this one here slash posts which brings us to the base URL and slash posts as the suffix and here we can find a very big JSON I have a separate five minute tutorial where I explain JSON in more detail which you can also find in the info card box by just as a summary JSON is the data format we use to communicate between our app and the server and it's the one that is most commonly used nowadays because other data formats can easily be turned into a JSON or vice-versa so it's a bit like English almost everyone speaks it and we can use it to communicate with each other without you having to understand German or me having to speak your language everything here that is between curly braces represents a JSON object which contains different key value pairs and this is the equivalent to a single Java object where the key on the left side would be the variable name and the value on the right side after the colon would be the value of the variable in Java and the soil JSON file is surrounded by square brackets which stands for JSON array which just like a Java array is just a sequence of multiple values separated by commas so this is an array of multiple JSON objects and in our app we will then turn this into a list of Java objects so we can already remember title body user ID and idea because we will recreate this later as a class in our Android project okay I have already created a new Android suitor project but I haven't changed anything yet the first thing we have to do is add the Gradle dependencies so we go into the Gradle scripts folder open build al-queda with material : app and from the retrofit these two dependencies I showed you earlier retrofit and the Gaeseong converter when we have added this we click sync no wait a short moment until it's finished syncing and then we are ready to go okay the next step is to create a model class for the single posts that we will then retrieve from the web service so we go into the app folder into Java open our package right click on the package and create a new Java class so each JSON object represents a post so we will name it post here as well we don't have to change anything else and click OK okay and reset that each post contains a string for the title a string for the body which is basically the text of this post and two integers user idea and idea okay so let's recreate this in our project first we create a private int user idea a private int idea a private string title and another private string for the body of but you will name it text here because I find this name of hitting and if the JSON key and the variable name differ then we can annotate this with Z realized name which is a G's on annotation and here we simply pass the key of the JSON and form of a string so now to JSON parser knows that our text string is supposed to be the body value of the JSON I have a separate video tutorial on G zone where I explain the features in a bit more detail it's not necessary that you watch this tutorial to understand the retrofit series but I would recommended ok and then we need to get our methods for these values so we can later get these values out of the post objects and display them in our app for simplicity we believed is that the methods out here because we don't need them and rewrite click on an empty place go to generate click on Guetta and now we select all four values by holding shift down like this and we click OK other generated these forget our methods for our four member variables okay that's our post class grief retrofit we will later retrieve the post array from the REST API and the Gaeseong converter will take care of turning these posts JSON objects into post Java objects okay until later display all this stuff in our app let's make some quick changes to our activity main.xml layout file down here we switch over to the text tab and we will display our data in this text view that we already have in a real lab of course you would use a recycler view to display a large set of data but for simplicity we will just use this texture let's make the text color black with text color hashtag zero zero zero so it's a bit better visible we give this text to an ideal android : IDL + ID slash let's call it text underscore viewer underscore result or whatever you want let's also remove the text entry wrap it in tore and nested squirrel viewer with match parent width and height because the texture will get bigger than the screen so we can use a nested squirrel view to make it scrollable we take this closing tag here cut it out and put it below at the texture so it's wrapped into this nested squall you to be give our layout itself a petting of ADP and then we press out control L to rearrange everything and format the code properly okay so we have the layout ready and our post class and the next step is to create a Java interface that then represents the API of the web servers in our app so again we right-click on our package and create a new Java class and since our fake REST API is called JSON placeholder let's call it JSON placeholder API and we have to change class to interface don't change anything else and click OK then we go into this interface and create one method it will return a cal object this one here which says retrofit tool we make up health angle brackets and for the type repairs list and not appeal finger brackets and then rewrite the post because this is what we want to get back from this car a list of posts which is a JSON array of post JSON objects that we saw earlier we have to give this method the name it's colored gateposts parentheses semicolon because in a Java interface we don't provide a method body we just declared this method Co and whatever later implements this interface has to provide a body for these methods and this is what retrofit will take health it will auto generate all the necessary code we need to get our list of posts back and to tell retrofit what to do or we have to annotate this method and this is the gate request which means that we want to get data from the server so we annotated with it get in capital letters parentheses and he repairs posts as a string because if we take a look at the URL again we see that it's JSON placeholder type a code calm slash posts this part here is the base URL and post is the relative URL the reason that we only define the relative URL in our interface is because we will pass the base URL at a different place later okay so back into our project we only need the relative URL where we get our list of posts from and this is already it for the end of his retrofit relator generate all the necessary code for this method and if you have watched my Android architecture components tutorial then this looks pretty similar to what we do with room that we also provide interfaces and annotate them and there they are called dull but with room it's for SQLite and refresher of it is for web services okay in this color object here and capsulate a single request and response so later we will use the skull object to execute the action get request but you will see this in a few minutes we will do all of this in our main activity so let's switch over to this class and again that we do it in our main activity is just for presentation purposes because this is not proper app architecture but there is no point in blowing this tutorial up with a lot of utter code so we keep it simple and the first thing we do is create a text to variable for our text result we have to sign it and uncreate takes result find you by idea the usual way and below we will execute our actual get request for this we first need an instance of retrofit so rewrite retrofit recolored retrofit equids new retrofit dot builder we don't put a semicolon here yet and I'm going to continue in the next line then we call dot base ul because as I explained before our interface only contains the relative URL and here's the place where we defined the base ul where we want to append this relative URL on and this is of course our JSON placeholder tobiko dot-com and form of a string no Seema : hero then we write ad converter Factory this is how we define that we want to use JSON to a pass the response and he rewrites G zone converter factory dot create and last week he'll dot built semicolon and rift this retrofit insincere we can now create our JSON placeholder API so below rewrite JSON placeholder API you let's color JSON placeholder API equals and since this is just an interface we can of course not call newer JSON placeholder API without providing the actual method implementation ourselves but this is the job of retrofit to rewrite retrofit dot create and paste the name of the class JSON payload the API titled class and retrofit will then bring life into these methods that we just declared without the body ok and to execute our network request we have to use the color object that I showed you earlier it's the red color again of type list of type host we call this wearable car equals then we take our JSON payload the API and then we can call our get posts method because retrofit creates the implementation for this method and then we simply have to execute a skull and get our response back super white collar dot but we don't curl dot execute because this method will run synchronously which means it will be executed on whatever thread we are currently on and we are on the main thread and if we try to two network operations on the main thread we will get an exception because this will completely freeze away up instead we have two executed on the background thread but of course we don't have to create this thread ourselves retrofit provides a convenience method for this which is called NQ and here we have to pass a newer car back maybe heaven on response Quebec and on failure on failure means that something went wrong in the communication with the server or processing the response for example when we make a typo in the base URL or when the JSON that we get back doesn't fit to whatever we are trying to pass it into for example when we try to pass a JSON array into a single Java object if this is the case we will simply display the error message on all texts or it's a red text result dot say text and here we passed here which is the throwable that we get past here throwable is just a superclass of exception and arrow and then Ricardo get message so if something fails we get a good idea on what went wrong we won't to anything else anon failure and I will take help on response and this method will be triggered when we get a response back from the server but this doesn't mean that our request was successful because the server code for example responds with a 404 code which means that whatever data we were looking for is not there and if you used in the net regularly then you already know four or four responses because you get it for example when you try to access a website it has been deleted so what we will do in here first is we will check if exclamation mark response which is the response that we get passed from this method the dot is successful this means that the HTTP code is somewhere between 200 and 300 entry found whatever we were looking for curly braces if this was not successful we will simply set our text to a result of the response code so we have an idea of what went wrong say text let's write code as a string and we append response dot code which is the HTTP code that we get back and then we work our return to leave this method right here because the actual data from this response will be now if this was not successful and if we try to do any operations on now as you already know we get an ID by the exception and our app crashes so whatever we write below does if statement will only be executed if our car bus exists for entry didn't get any other error so let's take a look at this response variable again we already know code and is successful and as we can see here body contains a list of posts this is what we actually want to get back so let's create a list of posts we colored posts equals response dot body this is the data that we actually want to get from the web service and then we want to display it in our text you we iterate through the single posts for post post : pause for each post in our posts list we want to append the data to our text you so we create a string let's call it content we set it to an empty string and then we append all the data content plus equals to append something to the string and then we want to append our four different values use the idea idea title and body so let's start with the idea ID colon space plus and now we can get ID out of our post object with our normal getter method like this let's also append the Nuttall string with backslash n so we make a line break and then we continue on the next line content plus equals and this is not an efficient way of building a string by the way but again this is just for presentation purposes next is the user idea and then the title and the text which is the bhadiya in our JSON and then I append two line breaks because then the next object starts visit us on our texture but not receipt eggs riff dot append so we don't overwrite each previous post and here is simply paste our content string and this is our first get request if everything went correctly we should get a list of posts from our JSON array on the endpoint we defined in this get post method in our JSON placeholder API and the only thing left to do is adding internet permission because otherwise we will get an exception so we go into our manifest file and here at the top above application right opening angle brackets uses permission and you use this one-year Internet / crossing angle bracket we are done so let's test it okay on the Left we can see the JSON on our posts endpoint and as soon as we start our app we should display the same data in our activity because we execute everything directly in oncreate so let me start this is the same data that we can see on this endpoint we used retrofit to load it from there into our app entry use JSON to turn this JSON array into a list and his JSON objects into Java objects and then we used our normal getter methods to get the values out of these Java objects and display them in our text you okay if this was helpful please if you like and don't forget to subscribe for upcoming parts of the retrofit tutorial take care you
Info
Channel: Coding in Flow
Views: 325,580
Rating: undefined out of 5
Keywords: retrofit, retrofit android, android retrofit, android retrofit tutorial, android retrofit 2 tutorial, android retrofit json example, android retrofit vs volley, android retrofit2 example, android retrofit tutorial for beginners, retrofit android tutorial to get json from server, retrofit 2 android tutorial, android retrofit tutorial 2018, retrofit android example tutorial, retrofit 2.0 android tutorial, retrofit get, retrofit get request, android get request, volley, networking
Id: 4JGvDUlfk7Y
Channel Id: undefined
Length: 20min 0sec (1200 seconds)
Published: Tue Sep 18 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.