Android Kotlin: Forecast App 02 - Retrofit + Coroutines + Gson Fetch API Data - MVVM Tutorial Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in the previous part of this tutorial series we created blank fragments we can navigate between them using the navigation architecture component library like this so here we are on the current weather fragment then we can go to future lay sweater fragment and also to settings fragment but all of those fragments to which we can navigate are completely blank and basically unusable in this tutorial we will add some actual functionality to this Android forecast mvvm app namely the ability to fetch weather from an API this means that in this part you are going to learn how to use retrofit together with jisang library to fetch and parse JSON data from an API the API we are gonna be using is a pixel calm which is a where api offering a generous and I mean a really generous free plan even though we are going to be using this epic su API you can apply what you learn here to any other API you desire so if there are any problems with a pixel in the future we will be able to switch to a different API really easily [Music] hello welcome three cell coder so first let's go over to epic SOCOM and the link is also in the video description and over here you want to sign up but I already have an account so I am just going to login once you are logged in you want to go over to dashboard and in dashboard you can see that our current plan is the free plan and if we click on change plan you can see that when we are using the free tier we have 10,000 API calls per month so we can fetch weather data 10,000 times per month which is quite enough so let's go back to dashboard and you can also see that we have an API key associated with our account so this is the API key over here 89 and something we are going to copy this API key later and please copy your own API keys and not mine but even if you copy mine that doesn't matter but you should really create your own account so that my accounts API usage doesn't get to bloat it now actually we want to copy this API key so just ctrl C to copy it and now let's go over to the interactive tab over here and we can paste our API key to this field make sure there are no spaces and we can query for current weather because in this tutorial we are gonna be implementing the current weather and then later we will also implement fetching the forecasts but for now let's just focus on current weather so as the query string we want to put some cities so for example London and now let's hit show response and here is our response and this response is in the JSON format and a bit up we have actually the call URL so if we copy this URL and open it in a new tab we're gonna get exactly the same JSON as we have gotten over here so actually this is the URL that we are gonna operate within our app through the retrofit library if I make this bigger so you can actually see something on YouTube you will see that we get two objects two JSON objects one of them is location and another one is current we are gonna get to location later because we are actually gonna want to operate with location because we want to show the currently fetched location and so on in the toolbar as you can see in the finished app here over here is Austin and today so this is from the location object but for now let's ignore this location object but we have a much more important object and that is the actual current well here we have the last updated time this is now really important for us but we have temperature in Celsius and also in Fahrenheit we have weather condition we also have the wearer icon as the part of the condition sub-object then we have the wind speed we have wind direction right north and also pressure precipitation humidity clouds if we if it's cloudy or not currently it's not cloudy in London it seems so then we also have the feels-like temperature also in Celsius and Fahrenheit and we also have visibility so there is really a lot so we have all of this data but we have it in a JSON format and as you can probably imagine this JSON format doesn't do us any good when we are working with Android apps because of this we need to convert this JSON to some objects which Catalan language can operate with and for that we are going to use the library jisan which is a library which can parse JSON into some real objects with which we can operate through Java or cotton so let's go to Android studio and let's open app Java in our package and then data and in the data package we want to create the classes which are going to be representing the JSON that we get from the API and we could do this by hand but that would be pretty exhausting because for every field that we get from JSON so here we have it here is field temperature C temperature F is day and for each and every field that you see here we would need to create an appropriate property in our Kotlin classes and that is pretty exhausting but thankfully we can use an Android studio plugin which will do this for us so first let's copy all of the JSON so hit ctrl a and ctrl C and now we have it in our clipboard and let's go back to Android studio and we are going to use an Android studio plug-in called JSON to Kathleen class you can get it by going to file settings and then plugins you want to search or actually browse repositories down here and you want to search for JSON to cut then class I already have it downloaded so you just hit install or something like that and you will have it in your Android studio after you restart and once you have it we are gonna right click on data package and we want to hit new and cut and data class file from JSON we are going to set the class name to be current weather response and we are also going to paste the JSON that we have just copied from the browser right so paste all of it in here we can also format it so we can see it more clearly you probably cannot see it on YouTube but it's the same JSON that we have copied previously and also you want to go over to settings and you can leave this to be keyword var and non knowable in the annotation tab you want to select G sound because we are using the JSON library which we have added in the first part because in the first part we edit every library that we are gonna be using over the course of this tutorial series and in other you want to make sure that you are creating annotations only when needed so make sure that this is sticked on and hit OK and hit make and here are the classes which were created by this plugin we have current wearer response so this is the root of our response because we have location and we also have current if we go over to locations definition by hitting control B we can see that everything is over here nicely set up but we are an interested in location so let's go over to current and actually before we go over there let's rename current to say current weather entry so that the meaning of the class is more clear so current weather entry all right and refactor everything but because we changed the class's name the name of our property has also changed but this can be a pretty big problem because if we take a look at our JSON output you can see that the object is named current and not current where entry so we somehow need to tell ji-sun library once it's parsing the JSON over to Catherine objects that the property called current weather entry is corresponding with the current field in JSON how can we do that well we can use an annotation so back in Android studio we can annotate the current weather entry property with at serialized name and the serialized name will be simply current as it's in JSON response and now the JSON library will figure everything out for us so now let's go to the definition of current weather entry so ctrl B and you can see over here that we have all of the fields here really nicely in the later parts we are going to mess with these fields a bit we are going to add some annotations for the room database and we are actually going to remove some fields which we don't need but for now let's not worry about any of this we are gonna modify this class in later parts for now just know that we also have a nested class condition which is also defined here it has text icon in code and that's about it now let's create a new interface a pixel weather API service so under data we want to create a new Kotlin interface a pixel where api service once we have it we are going to also create a new package under data and it will be a response and we are going to put all of our response classes so everything basically except of for the epochs aware api service we are gonna pull it over to respond package and this interface a pics aware API service will be used by the retrofit library to fetch the data from the API let's go back to the browser for the last time and let's go over to our dashboard so go to home and my account yeah and dashboard and over here you wanna again copy this API key and now back in Android studio we are going to create a new constant so Const Val API key and it's going to be equal to this as a string I also copy the query URL so we can actually have some kind of a reference 1 when we are creating this API service so this is how the query URL looks like so first up let's create a new function for getting the current weather and we will call this whenever we want to get the current weather right so fun get current weather and this will be a get request so an annotation get and we want to get the current dot JSON because this part the HTTP epochs API epoch sukham v1 will be handled in a different part of code and this query will also be handled in a different part of code so over here in this get annotation we only want to specify the current dot JSON so let's put it over here and over here in the parameters of this function we want to specify these query parameters actually not all of them because the key will be handled in a different part of code which we will get to in just a little while but for now we want to specify this Q and this Q is a query parameter for the city so we want to specify a city so we want to add an annotation here so add query its string is Q and Q stands for occasion or a city so let's put over here location which will be of type string and just like we have Q over here we can also have another like end and then Lang for example equals en for English so this is language and English so we can also have this and because our users can be speaking some other language than English we also want to put it as a parameter of our get current weather function so again quarry at query lang for language and we're going to call this parameter language code and it's also gonna be of type string and the value of language code will be English so en by default so if we don't pass any language code to our function call it's gonna be automatically assigned to be English and what is this function going to return well fetching data from an API which is located somewhere on a distant server takes some time because of this we cannot just simply return current weather response like this right because this is actually returning current weather response but we cannot return it directly but we need to wrap it inside a deferred right so the firt and its generic type is current well response the firt is a part of cover teens and we can wait or actually await a deferred so whenever we call get con weather after the call we can put a wait in the cutting compiler will handle everything asynchronously for us and once the con wear response is ready we can start working with it the third is part of the code lens cover teens and if you want to learn more about catherine's cover routines i have a separate tutorial about them so you can check it out by clicking on the card in the corner but having just an interface is not enough we need to have some kind of a class which will be operating with this interface and that class will be actually fetching the data from the API for that we are going to create a companion object for this interface and companion objects are basically like static methods and this companion object will have just one function and it will be operator function so operator fun and its name is invoke and it's going to return a picsou error api service so this precise interface here and it actually doesn't need to be operator fun invoke it's just here because the syntax for invoke is really nice for example if this wasn't an operator fun invoke but it was just fun create for example we would need to call a pixel where api service dot create write and that's how we would call the create function but because this function is called invoke we can call it by simply writing epics aware api service and then do parenthesis and this is the same as calling that invoke so operator function invoke is just really nice syntactically because we can call it like this as if we were instantiating a class alright enough about invoke and now let's look at how we can actually put this API key into every single call of the epics aware API service we could also hard code this API key over to this call so just putting at query right at query and then key and then the value of the key as the parameter but this is not a good practice when some value is passed to the query string every single time that it's called it's better to pass it in there with a request interceptor so over in invoke let's create a new valor request interceptor and it's gonna be equal to interceptor and this is an anonymous class with only one function so we can use the lambda syntax like we are doing now and this will pass as a chain so chain and now we want to add this key this API key as a query parameter so we want to add it to the URL which is currently intercepted because request interceptor intercept requests how else so we want to get value RL and it's gonna be equal to chain that request and on this request we wanna get URL then we want to have a new builder because we're gonna use this builder to add a query parameter and this query parameters name will be key because as you can see here it's name is key and the actual key which we want to pass over here is the API key which is our constant defined above and once we have this query parameter added to our URL we want to call built on this new builder then we also want to create Val request and this is also going to be equal to chain that request and now we want to call new builder directly on this request and we want to set the URL to be our updated URL because we have just added a query parameter to it so let's add the URL and now call built and from this interceptor lambda from this whole lambda we want to return so return at interceptor chain that proceeded and we want to proceed with the request that we have created and this request contains the updated URL and this updated URL contains our API key now we actually want to add this request interceptor to a class called okay HTTP client so that it actually intercept every single call so let's create Val okay HTTP client and it's gonna be equal to okay HTTP client that builder and we want to add interceptor on this builder and our interceptor is called request interceptor and then we want to call build alright in the final we want to return a pixel where API service from this invoke function for that we are going to create an implementation of epoch Seur api service through retrofit so we want to return retrofit that builder and on this build we want to set the client and also import retrofit so alt enter and import and the client will be set to ok HTTP client which contains our interceptor here right then the base URL for every single call will be this so HTTP API a picsou comm v1 and also this slash over here so let's copy it and paste it as our base URL so this is the base URL of every single call that we make and actually we can also make this HTTP so that it's secure but it doesn't really matter you can leave it at HTTP 2 and you will be just fine then because we are using the firts over here we need to specify a call adaptor factory for the retrofit library so we want to call an error function and it's called adapter factory add call adaptive factory and adapter factory that we want to add is call routine call adapter factory and this is from a library which we have added in the previous and the first part we also want to add converter factory because we are using jisan so we are basically now telling the retrofit to use jisan to automatically parse the json string into some real catalan objects so jisang converter factory the create finally we want to call build and now we want to call create and we want to create an implementation for a class a pick zoo where api service and we want to get a class java from our interface alright so I hope that ever is clear you can also get the code from the link in the video description so that you can look at it in more detail when you feel like it alright and now we are going to do something which you should never ever do in a real production app and we are actually gonna fix what we are about to do in later parts but for now let's just have something tangible so that we can see if this epics aware API service actually returns some JSON so let's go to the UI package and whether we want to go over to current weather fragment and for now we are going to skip all of the steps like view models dependency injection repositories and database and all of that stuff because we are going to use our epics aware api service directly from the fragment just for demonstration purposes so over in an activity created let's create a new instance of epics aware api service so val api service is equal to a pic zoo where api service and we can call the invoke operator function really simply here we are going to launch a new cover teen on global scope and this is also not how it should be done but again just for demonstration purposes in later parts we are actually not going to be using global scope but we are going to use a scope specific to every single fragment but just for now let's do it with global scope for simplicity so we want to call global scope that launched and we want to launch it with the main dispatcher so dispatchers that main because we want to be able to operate with the UI and main dispatcher allows us to do some things with the UI in the launch cover teen scope this is because on Android you can only update the state of the UI so text views image views and so on only from the main threat and over here we want to simply create Vow current weather response and it will be equal to api service which is our a big sewer api service that get current way the location will be for example again London the language code will be English so we don't even need to specify it over here and then we want to call a weight and then we want to get textview and actually in order to get it we need to go over to rest layout and current weather fragment and we need to add an ID to this text view which will be at plus ID simply what's a textview and let's go back to current weather fragment and we want to get the text view and we want to set its text to be equal to current wearer response dot current weather entry and then also that two string obviously so let's run our app in an emulator and we actually get an error so let's see what's wrong so let's go over to lock CAD down here and let's change this to error oh and over here we can see fatal exception ok HTTP dispatcher that we are missing Internet permission and surely we are missing it so let's go to Android manifest over here so manifests Android manifest and over here let's write that uses permission and the permission name is Internet and now we should be all good to go so now let's run the app again and yeah it surely works because over here we have I don't know if you can see properly but we have current weather entry the last updated epoch and so on and let's actually go back to current weather fragment and let's not print the current weather entry but let's print the whole current weather response so that we can see the location to to check if we are actually fetching really fetching for London so let's run it again and yes once the app is running we can see that the location is London the region is city of London and so on alright so that's it for this tutorial if you don't want to miss the future parts of tutorial series in which we will be implementing the UI of the current weather fragment and also the repositories and also the database which will cache the current weather entries subscribe to this channel and also hit the bell button so that you get notified about all of my new videos if this video helped you with understanding and implementing the retrofit library and also together with jisan and fetching weather data from some API give this video a like and also share it remember that you can get the code from the link in the video description follow me on Instagram Facebook and Twitter leave a comment if you have anything to say if you have any suggestions or questions and see you in the next video [Music]
Info
Channel: Reso Coder
Views: 70,576
Rating: 4.9234304 out of 5
Keywords: resocoder, tutorial, programming, code, programming tutorial, android, kotlin tutorial, kotlin android tutorial, kotlin, android mvvm, android mvvm tutorial, android mvvm architecture, android mvvm design pattern, android room tutorial, android room database tutorial, android retrofit, android retrofit tutorial, android coroutines, kotlin coroutines, kotlin mvvm, kotlin mvvm android, kotlin kodein, kodein android, kotlin android
Id: RSYTn-O3r34
Channel Id: undefined
Length: 27min 40sec (1660 seconds)
Published: Sat Oct 27 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.