Java Android App using REST API - Network Data in Android Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi in this video we're going to talk about network data and how it works in android and then i'll prepare you for a tutorial that's to follow [Music] so there are three things that we're going to examine in this video we're going to talk about what a rest api is then we're going to talk about how to program what's called asynchronous code and then finally we'll talk about the volley library so rest api is a term that you'll see in programming languages everywhere it's really about clients and servers the api stands for something called an application program interface and really in plain english it means that there's a server somewhere that's providing data to the client so that way you have either phones computers or watches or something out there that is relying on a service on the internet in the following videos we're going to create a tutorial in android using a rest api from the service called metaweather.com and so we're going to have a service that looks like this where it provides you with a weekly forecast and it will be up to us to design the user interface so that that data comes out and looks good so a rest api is a service that lets you look at specific urls such as the address that you see listed here and instead of responding with an html page a web page you get a back a a pure data form so it looks something like this here where it says london city and an id number so rest apis and microservices are two terms that often appear together so sometimes a development team will break up an application into pieces into micro pieces you might say and they use apis to talk between those pieces so a server can usually be split up into tasks so this is a traditional model you might see so we have at the bottom we have a database we have a data interface we have a business logic and then the user interface a multi-tiered approach well in microservices you might say well that one data interface is actually could be split up into multiple pieces and we'll call them microservices microservices can talk directly to the user interface or they might provide data to other microservices so that way you can have a modular approach to building your program the link between those is the api so the text messages that are traded between clients and servers are usually done in two different languages one is json and the other is xml there are others but those are the two most common so this is what json data looks like you can see that this is a weather report and you can also see that it is very easily understood when you look at it tells you what the id number is the type of weather that's for the day you can see the minimum temperatures the maximums it's pretty much readable as a human would be able to see it but you can also see that there are specific quotations and colons and so it's a very data delimited piece of text now the same data could have been created in an xml format and so the xml format looks a little bit like you just expect a web page it's a hypertext it's got these brackets and an open and enclosed tag and so they're not exactly doing the exact same process xml has a little bit more functions to it and it's not as popular either so most people are working on the left side here with json data in their apis so json stands for javascript object notation and it can be configured to send messages in not just json formats apis can be in others but usually json is the type of data that you would expect to see it's really common and despite its name json is not limited to javascript so json can be used in many different programming languages so if rest is associated with json then the terminology soap is usually associated with xml so soap stands for simple object access protocol it it's very similar to rest but you can only see xml data when it comes to soap so you could see json being used with rest and xml being used with soap but they're both pretty much producing the same results here they're both trying to communicate text messages to a client so let's talk a minute about the client and the server so the client's job is usually the one that says i will initiate the request i will ask for some data and the results will be sent back into the the format that the client can understand so we're going to follow this video with a tutorial that will show you how to use the client for android so your client could be a phone it could be a desktop it could be a watch it could be another server but the client and server is just kind of a generic way to think about it so that we will use a phone here in our example but in other cases we could just as easily have programmed this as a web page so what does an api look like so the rest service usually have some kind of an end point that provides access to the client so in this example we have a url from the website metaweather.com api location and then a location number and then what follows from that is the weather report for that specific id number which happens to be the city of london and so in a traditional web page you would at the green part of the stack of items you would have said this is the web page in a rest service we would say the url endpoint is not a web page it's just pure text and then the client is responsible to format that text into the proper user interface so how much work does it take to create a back end does it have to be written in android is have to be written in java what's the language well the truth is it doesn't matter what the language is and server applications can be written in php c-sharp they could be written in java node they could be written in ruby python pretty much any language that can create text files and call and communicate with a network is going to be eligible to make rest services so the middle part here in the business logic can be any language that you choose it's pretty much irrelevant and so your team sometimes are split up as a back-end developer and a front-end developer and that's thanks to the ability to create these apis that can bridge the gap between the front and the back end now since there is such a nice standard with json you can format the data to be output no matter what language that you're working with and so we have no idea what metaweather.com used as their backend whether it was java c-sharp or something else now think about the amount of effort so the ui the user interface in the front end approximately takes about half of the amount of effort that it would take in the back end of course that determines that's determined by the complexity of your application sometimes the back end is really the secret sauce of an app and that's what would take the majority of the time so if you're interested in learning how to create the back end i have other tutorials classes on php classes on java classes on c sharp and all of those using their frameworks and their full stack will allow you to see how to create the database and then the urls that are providing these services to you but for the sake that's going to follow here we're going to create an android application that is going to use a pre-existing free open source api so we will only do half the work really for this weather app another feature that you're going to see in this application tutorial is that there is the idea of asynchronous code now in most examples of coding you're probably used to seeing synchronous code that means one line follows the other you can trace through exactly the order of statements in a program however with callbacks or asynchronous code we have an external process going on and that's why in network programming here the idea of asynchronous or callbacks is going to be super important so let's take an example here so i have some code in this gray box and its function says get me some data and it says i want to go to a website a url an api let's say and i want to get some user data so it looks like we're looking for user number 99 now that's going to take some time because of the network traffic and it's kind of could be on the other side of the world it might take the couple of seconds for that response to happen and so we're not going to sit around and wait for it we're going to jump right into the next item in the in the program so we're going to continue running that's the synchronous mode and we're going to just forget about our network request and let him catch up later now that catch-up later process is called the callback and so when the process is done there will be an alert sent to your application that says hey data's arrived and what do you want to do with it so the callback function will have a parameter like a list or some kind of a string or something and that will say hey i got the data back from the server and now in this green or in the sorry in this red processing box here you can go ahead and process process that data it means you can save it to the database or display it to the user or whatever your choice is but the callback is going to occur at some later time and we're not sure if it's going to be a millisecond later or a minute later but it will be a delay so let's take a look at actually some of the code that we're going to develop here so we are going to define a callback function and it will run after a set of data has successfully been retrieved from an online service and so here's what it's going to look like we're going to have a button click for get weather by name and we are going to call this a service called the weather service and it's going to get the forecast so it's some function and it's an asynchronous function so following that we're going to have two options so when this is done we are going to have a on error that's a possibility that nothing came back or it was badly formatted or we're going to have a response and you can see in the response that i am updating an arrayadapter so i'm showing a list on my ui so this is the actual java code that we're going to be coding in a tutorial in the next video so this asynchronous process is going to help us with what's called non-blocking code so non-blocking code is to allow other tasks in an application to continue running and not block up the user interface so you can see in the example in this timeline here that we in the first example would be a synchronous execution so we stop all processing and wait for our response however in the second example below you can see that we are going to start the external process the network request but then we're going to go on and do other things we're going to keep processing the threads you might say and uh we're gonna have things going in parallel and so it'll prevent the application from freezing up so the first process will continue executing and then the other code will work in the background in android and in all applications the user interface thread is important not to block so we have a task list here you can see i've got four applications running on my application we don't want them to stop there is a literal loop or a looper they call it an infinite loop a while loop that continually checks on each task and gives each task a little bit of processing power so it's the scheduler in the operating system now if we were to stop one of those tasks and it had to sit and wait for a response then your whole phone will freeze and it'll appear like your application is dead you might get an application alert that says the process isn't responding what do you want to do close the app you might want to and if the user does that then you'll probably never come back to your app they'll call it a buggy app and you don't want that to happen so in instead what we're going to do is we're going to use this interface thread which is responsible to keep the user interface running we're not going to mess that up instead we're going to offload this to a background task and we'll let that handle the retrieval of network information and that way the looper can continue to go on and the user can continue to choose menus and buttons and just wait for the weather to get updated in the uh in the second app now to do all this network requests and all this looping and background processing there are libraries that are built to help handle these kind of things so android has several libraries available to us there's one called volley and another one called retrofit so volley is the official documented library that you would find on the android tutorials and that's the one we're going to use it's been around for a long time however there's another one called retrofit and it's actually probably more feature-fold it might be a little bit easier to use and it's actually shown up recently in the process called the jetpack so jetpack is a as a collection of libraries that are considered best practices by google and so even though we're not going to use retrofit it might be a better choice for future programming but they they work very similarly so the concepts will be the same in either library so here's what's ahead of us we're going to create a weather application using an api and an android so we're going to install the volley library we're going to parse a json data feed and then we're going to use asynchronous methods using callbacks to update our user interface and so all of that stuff is just ahead of us so let's take a look at how to build a weather app using android hey welcome to a new series of videos we're going to do for android development as you can see i have an app on the screen and i'm going to show you what it does so if i type in the word of a city like phoenix and choose use city name as my button i should see a list of temperatures weather reports and so that's what we're going to make in this next few videos [Music] so this weather app is going to demonstrate how to use rest api services and so you can see that i've got the current temperature and the current forecast for my city you can see the phoenix weather is pretty boring it's clear clear clear clear clear and some showers perhaps it gets pretty hot here so we're up to that's celsius that's 43 degrees so the type of data that i'm going to get looks like here so for instance if i do a search for the query of the city of london i'm going to get back a json report that looks like this it's going to have an array and an object and then you can see i have london and then this important number here which is the id number for this city so i'm going to copy that number and we're going to use it in another api endpoint so let's scroll down here and see what what this would do so for instance here i'm going to choose this example for london and you can see the number 44418 is for london and the weather report then shows up as a series of text really it's json and then some other things that tell us about where we got the information from and what we're going to do is turn this into an application that runs on android and so you can make your own weather report app so let's see what some of the other things that i've programmed are so if i type in the name phoenix again and choose get city id you're going to see a pop-up that says the id number down here so let's go back and try what they gave us as an example here london so london england i assume and we'll choose get city id and you can see 44418 is the number so now i'm going to choose 44418 as my entry and the second button says use the city id and now you can see that i'm going to get a report for the london weather so that looks like it's probably correct light clouds heavy clouds showers that's not phoenix and then finally the last part where it says city name if i change this to london it's going to use this api twice it's going to first of all look up the id number and then it will re-submit the id number in and give us the weather report so we're going to go from simple to more complex you're going to see some things in this tutorial that will teach you about rest services how to consume apis and how to do some callbacks because this is like an asynchronous function so this is a little bit more advanced programming when we've got online services involved so i'm going to take you through step by step on how to build this application we'll start with showing how to create the layout and then we'll install the volley library which is used for getting online data like we have here and then we're going to program each of these buttons so the first one is simple the second one one's a little more complex and then the third one is a double call to the service so go simple to more complex and by the time you're done you'll understand how to use rest api services in your android application hi in this video we're going to go through the process of creating the layout for the application you can see here it's a rest api service that will turn into a weather app so the first steps that we're going to do is create a new project we're going to create three buttons a data entry line and then a list and so that's just a hit so i'm going to start a new project so you can see everything straight from the very beginning so let's go to android studio i'm going to choose an empty activity project and let's give it a name so i'm going to name mine as weather api app you can see the package name is the name of where i work which is grand canyon university my name and then weather app so this has to be a unique string this is usually the format that people work with the location you can save to any point on your hard drive likely in your documents folder make sure that you choose java kotlin is the more up-to-date language but java still is by far the more popular and i'm not quite sure what the minimum sdk is for java so i'm choosing 21 which is pretty much covering everybody out there so 94 and then i'm ready to click finish all right you can see that the little time has passed and the project is up and running so just to refresh your memory we've got ourselves two files that are important when you start a new project there's the activity main i'll double click and you can see that's the layout and then the main activity java file is where we do the coding so in this video we're going to modify the layout and we're going to create something that will look like the final product so the first thing i need to do is just delete the text that's there so i will select hello world and press delete now i'm going to put in three buttons across the top all right so now the tricky part of getting these three buttons spaced out is to manage their constraints properly so for the first button we're going to put the constraint to the top of the screen and to the left for the second button we're going to have the top of the constraint match the top of the first button and then we're going to do the same thing for the third so now i've got i'm trying to adjust these so i'm changing the margins to zero so there's no extra padding but i'm having trouble linking them left and right so they're all lined up at the top but i think i need to go into the text area so instead of looking at the graphical view i'm going to switch to the code view so this brings up the xml and i can manually put in the things that i need to do here so let's see button one is which guy the first one right here this is button and let's make sure we got the constraints right so the start of the button is to the start of the parent now the end of the button goes to button two that's correct now let's go to button two and let's see so his doesn't have a beginning constraint so i'm going to manually add that so i'm going to type in the word start of and you can see that it automatically provides me with a type ahead so i want to do the first choice that can the start of this button is going to match the end of the previous button so i'll select the first one and now it says which button do you want to select so this first one all right so now the end of the button is going to be constrained to the start of the pre of the the third button that's correct and the top should match the top of the first button okay so i believe button two is in the right spot let's check the graphics there you can see the button one and button two are evenly spaced and this uh kind of wavy line says this is there's a two-way constraint going on now we need to add the constraints for the third button to spread him out so let's go back to code and i'm going to do the same so let's see let's check the constraints so the end of this button goes to the end of the parent which is the right margin that's correct the top of the sky matches the top of button two so yes they're horizontally uh they're going to be the same vertical distance down now i want to change the constraint to be the start of this is going to be to the end of the previous buttons so i'm looking for start to end of and now it says the end of who that would be the end of button two which is the center button all right so now we have a end start and top that looks good to me let's check the view in graphics now and they are now all evenly spaced so that's kind of a tricky thing how to get these spaced across evenly all right so now i want to rename these instead of button button two and button three i'm going to give them names that match the purpose for which i'm going to program them so i'm going to switch to this middle button which is called split and you can see the xml code and the layout here on the right so i want to modify this first button here and his name is currently button so i want to change his id to btn underscore and then his purpose which is get city id and you can see that all of the constraints just fell apart that's because down here in the second button you can see it's still thinking that button is the guy he's supposed to be attached to so that doesn't work obviously so i'm going to copy and paste this id number over top of those and now the constraints are back to normal good okay so now let's change the id number for button two so he is going to be btn and his job is to get the weather by city id so when you click this we're going to have the ability to translate an id number to a city uh weather report so that's why we get get weather by city id and you can see i'm going to copy this and the reference down here needs to change so paste over top of that and paste over top the second one and they're back good all right so what happens this one needs to be pasted so i'm replacing the id numbers let's see the third one is button three and so here is going to be btn and we're going to say get weather by city name so you can see the difference this one was city id we're going to provide the name of the city here to get the weather report all right so let's copy him and replace this reference here to button three and i believe that is now balancing out correctly so that was a little tricky but we got all of our buttons in a row and we changed their id numbers all right so now we've got to give the button text something better than what we have here so the text is there anything in here about the text there is not a property listed in the xml for text so let's go back to the graphical view and i'm going to select the first and let's go check the properties so here is a text property it says button so we're going to say get city id is his name all right so that changed the text property this one here is going to be get weather by id number and then the last one is going to be the same it's get weather by name and let's see they are not quite fitting so let's change this and i'll just say get gets out of the way and we'll say whether by id and the other one will be weather by name and there's just barely enough space so that probably will work now that's the buttons let's go to the next part which is a text edit so plain text is what i'm looking for and i'm going to drag him in and you can see why i called it edit text because that's the default name or the id let's put the constraints in so i want this to be attached to the left margin and the other end to the right margin and now i want the width to be the full width so let's change the width to 0dp which is also known as match constraints so it spreads out to the full width now the top of this thing let's match it to the bottom of the first button so let's see we want the top to the get city by id bottom and then it says i'm automatically going to leave you an 88 pixels margin let's just change that to 8 so it's pretty close that looks pretty good now let's give this a name so instead of edit text we're going to say et underscore data input so it's a generic data input we're going to use it to capture names and numbers so i'm just going to call it et data input now let's see down in the bottom we're going to see a text area so it says name i'm going to delete that and for hint i'm going to say city name is a good hint and now we've got city name listed all right so the last one is a is a list so i need to go to the common area and you can see that recyclerview is the common most recommended thing if you want to use a list view if you want to display a list of any items and scroll through it recyclerview is the recommended way now you can do that if you like however there's a lot of extra code and steps that are involved compared to a legacy option so even though this is legacy i'm choosing list view because it's so simple now the advantages of list view are its simplicity but the disadvantage is if you start adding hundreds of items to a list it will run very slowly and consume all kinds of resources on your app well i know that on my list i'm only going to have five items and it's so simple to program i'm going with list view all right so let's do the constraints here so the top of this has to match to the bottom of the data input and let's leave a little space here let's go 8 pixels let's go with the left side to match the left here and the right side equally drag to the right alright so you can see the constraints are here the start is the start of the parent end to the end of the parent bottom top is to the bottom of the data input and i'm going to leave off the bottom constraint now because it might just fall off the edge of the screen without any trouble all right we give it an id let's call this thing lview for list view and i'm going to call it weather report or weather yeah weather reports i'm going to use the the plural for more than one all right so that gives us a idea of what's coming now let's just run this and see what it looks like all right you can see that the it says gradle is finished my rest api changes to the new app and it says weather api app so you can see that i have three different buttons i have a city name so i can type in something here and then when we're done we're going to be able to generate the city's weather report down in the list view below so that's the first step now this is kind of a tedious process so i'm going to provide you with the xml file which is this code right here so you don't have to retype everything like i did and that will adjust any for errors if you've got any so under the next video we're going to start creating some button listeners so that way when these buttons are clicked they do something so that's coming up soon hey welcome to the third video of our application for doing a weather report as you can see in the previous video we created a layout in this video we're going to create some button listeners so that each of these buttons are now active [Music] so let's get started with creating some code that makes these buttons work so i don't need to look at the xml file anymore so i'm going to just close that and let's get into the code here which is main activity java you can find that here in the folder called java and then the first project folder and main activity so the first thing we need to do is get the values of all the buttons and their id numbers so the first three things that i'm going to capture are the button names so let's put in the button class and then i'm going to assign a value for each of these buttons so we can program it so btn underscore city id get weather by id and get weather by name i think those are pretty close to what i named them in the layout they don't have to be exact but it certainly helps if they are almost exact the other two controls on the screen are the lists view and the edit text so edit text is et data input and list view i'm going to call lv weather report all right so i've got those three uh categories here and it just occurred to me that these are all in the wrong location notice i typed them inside of where it says on create so i'm going to control x to cut them out and move them up so that they are now class member variables they're called so these are accessible for all of the code that will appear in the main activity so that makes it much more easy to program all right so now when the oncreate method is called we're going to assign these things a value so let's go one by one all right so let's get the first three buttons so btn underscore city id equals and we're going to find its id number so we use the word find view by id and r dot i id gives us the resource value so that's what r stands for resource id number and then the name that i assigned it in the layout and the other two are just the same so we're going to use find view by id and try to match up the values in the in the layout and give them a value here in the program the same holds true for the edit text and for the list view so we use find view by id to capture the actual number that's assigned to these so this is an integer that is it is stored into the actual button variable and the edit text variable and the list view variable so it's a good idea to comment your code just in case there's somebody looking at it that doesn't understand it as well as you do so i'll just say this is assigning values to each control in the layout this is pretty standard ideas so hopefully you've seen this before but if it's your first app maybe not the best choice for your first stat but i'll help you along the best we can all right let's move on to the next part where we're going to actually now create some listeners so the next section is going to be click listeners for each button so that way when we click them we know we have something going on so the next section we are going to create the set on click listener for the button and you can see there's type ahead code that makes us much easier so we'll have a new on click listener that comes out of this this is a what they call an anonymous function where it doesn't have a name it just has the inline definition and inside of this code we can create events now if the button is clicked so the best way to test a control is sometimes just to put in a toast let's test this one out to say you clicked me i'm going to check the rest of these the same way so for each of these buttons i'm going to do the same process i'm going to add the method called onclicklistener or set unclick listener and then inside of the parentheses we'll create a new listener event and for each of these i'm going to create a toast message so that way it tells me that i've been clicked and you can see that i'm going to now modify the actual text so we can distinguish between each of these items so i'm going to run the app again so i'll click this little circle arrow it'll restart the app and then we'll test out each button so let's test this out if i click the first button nothing happened if i click the second button it says you clicked b2 that seems to be working and third seems to be working so this is why you test out your code as you run something went wrong with button one what was the matter with it something didn't happen correctly let's just double check everything and make sure we got the name so the button name is called get weather by id and that is also down here so that is the incorrect name so let's try that again btn let's do by city id and let's save that i think that might be better because we had two click listeners for the same button and obviously the second one wins the first one was ignored let's uh let's try that again all right so we're up and running let's go and choose get by id and what happens now so now we have a you clicked me one you clicked me two hopefully comes up and three got all of them now let's do one more thing i'm going to put in the city name here and then we're going to echo out the name of the city as we try each of these buttons so let's go and grab the value from the weather by name let's see this would be a good one the third button we're going to add in some new code so instead of you clicked me 3 i'm going to put in this you typed and then i'm going to put in the value that comes from the edit text so let's do et input data dot get text and then i'm going to use a tostring method so that should get the text that was entered into the edit text and then re-displays it on the toast let's see what that does okay so we're up and running now let's put in the word kansas city how about and let's then if i could type correctly and let's try the third one that says get by name and it says you typed kansas city so that seems to be working so we've got ourselves button listeners we have the value of text that comes from the data input and now we're going to actually go and do some coding that will get the values from the weather report service hi and welcome to the fourth video of our series on using api services with android studio we're going to translate the text that's over here on the left side and put it into the app that's over here on the right side [Music] so in order to get actually produce a something that's sensible from the data on the left side we're going to have to get some tutorial information on how to use a library called volley so to help us through this process of using volley i'm going to the actual developer documentation from google so developers.android.com training volley that's what we're looking at so the section that we're in right now is called transmitting data over the network using volley there's actually something previous to this if you're interested how to handle general network traffic so this is kind of the overview of the old way or the pre-volley way that was done things and this this will work if you want to go through this process however google is recommending that we use a library called volley and it's right in their official documentation so let's go see what it says about what we're going to do so volley what is volley volley is an http library okay translate what that means is we can take a library extra software install it into into our project it will handle http traffic or let's say it will be able to handle text that comes in this format this json text and then it will translate it into something that we can use in the app so it is it's it they work they use the word easier and faster easier and faster than what it's easier and faster than the previous section called network operations and it says volley is available on github well we don't actually have to go to github to get it we can use it right in our dependency manager so come down to this section that says implementation and it says we're going to copy version 1.1.1 nice number there now we're going to put that somewhere let's go back into our android studio so to put in any dependencies we go down to the section called gradle scripts so what is gradle gradle is a dependency manager and we want the second option double click here so a dependency manager takes a look at the code that you see at the bottom of the screen you can see i just pasted in the new volley library everything that is in this list called dependencies is automatically downloaded from their source which is probably github and it copies all the files to your project that you need and then those libraries magically are usable in your code so there's a lot of work done behind the scenes you don't have to download and install files the dependency manager does that for you so it's going to say go to this website find volley version 1.1.1 now there might be newer versions out there but google documentations are using this so let's let's choose that as soon as you add anything to the dependencies list you'll get a message at the top of the screen that says gradle files have changed since the last project sync a project sync may be necessary well maybe is kind of a strange word it will be necessary so let's go ahead and click the button that says sync now now at the bottom you will see a message that says your status is finished so something was just installed on our program all right so everything looks uh green there's no problems so let's move back to our documentation so it says now we've done this uh you can also okay we're not gonna have to do that okay we have some lessons in here how to create a simple request a request queue a standard request and a custom request all right so looks like we'll start at the simple and then we'll build up from there so the process that you're going to see in the next few videos is we're going to create things a simple way and then refactor it to be a little bit better for more scalable programs so some of our code is going to start to look like spaghetti code and then we're going to separate it into its appropriate classes and when we're done we'll have a pretty decent looking app that is modular and that way all the pieces are kind of in their own place let's start with the first one that says send a simple request let's try that so a simple request means we're going to go and get a weather report so here is some code that we're going to work with now we're going to modify most of this but we will have a pretty good idea of how this works by the time the video is over so before we get to that it says you need to add the internet permission to your app's manifest so android permission internet let's go check that out so i'm back into my project and the manifests are up here in the folder called manifest let's go and open that xml file so we're ready to add the permission into our manifest file so right up here before the word application i'm going to start typing i'm going to use an open bracket so like the less than sign and immediately the type of heads helps telling me there's things that you can put here what are you looking for and what i'm looking for is the first one that says uses permission and isn't that nice it provides me some type of head code that says what do you want to make this application access well internet is the key because we are going to be looking at data that's online so let's close the tag and we could use the tag closing as it's here or i could just put in a slash and that's a self-closing tag so either one of those is acceptable so now we will automatically get permissions this doesn't require the user to click anything so there's no special code to see if they've approved or denied the permissions so internet permissions is pretty standard so there's just one line of code okay so now we've got ourselves the permissions now we're going to come down to the request queue and let's see what all this is going to do so we need to have what they're going to ask to fill in a text view we don't have a text view we're just going to use a toast but it's almost the same i'm going to copy all of this right down to the last line so i'm leaving out text view and i'm going to copy and bring this right into my project and where am i going to put it well i'm going to put it in the first button so the button here has got the first click listener and i'm just going to paste everything inside there alright so a whole bunch of stuff just turned redline we're going to have to add some new libraries it looks like so when we click the button the first thing that happens is we are going to initiate something called a request queue a request to what a request to the service online and so the queue means that you can't like have simultaneous requests they have to get in line they have to take terms so the request queue is this object that's going to be like a a lineup so it says here if you want to import the class we'll do that so we just imported it there should be something new under the imports so do we have a request queue yeah line 12 says we just imported this from the volley library so remember we have volley as one of our dependencies if we didn't put in the dependency down here in gradle then this exercise would have not worked right now so we've got ourselves the first line fixed now the next item says we're going to use an object called volley and that also needs to be imported so let's see if i can press alt enter and it says we've got a new request now what's going on here it says the context context says this doesn't work so what's the matter with it it says your context is supposed to be of the main activity context okay so context is real confusing if you want to see a previous video on context look in the playlist here i've created some android tutorials on understanding context anyway the context tells you where is this thing in the program so i'm going to type in the word main activity which is this class file and then dot this so that is the context of where this is being called from it's being called from main activity all right so what's the string well it's not from google.com let's delete that and let's go get a string from somewhere else so i'm going to go back into my browser and i want to get this string from one of these api services so let's go find out what that would be up here so i want a string to look like this here the one that says query equals london and so i want to get the id number of the city so this is the one that's going to work so i'm going to copy this whole url so let's do right-click and copy and we're going to trim off the last part that says london but we'll use most of it so let's go back into our code here and for it says string url we're going to keep it as london for now just to make it simple so this will only work for the city of london all right so now we've got ourselves a request and a url so the first thing it says is we're going to get a string request now there are different types of requests that we can use string request is the one that we will probably not use what we're going to ask for is called a json object request or a json array request because as you look at this data this is clearly json formatted data which is java object notation and so we're going to skip this string thing in just a minute but for right now let's keep with the code as they've given it to us so string request let's do alt enter and we'll import the class okay so we also have to do this other alt enter keep importing these things okay got it all right so here's the part that says text view let's get that out of the way and the response of the substring so let's just take let's take we know that the response is coming back and it's going to provide the first 500 characters well i'm going to just delete all that and the comments so what i want to do is just display the whole thing so i'm going to put it into a toast so i'm going to use toast again and let's go to the text here and say instead of the string i'm just going to put in the word response so what comes back from the response will be texted out in a toast all right so now we have an error listener so let's go and import these it looks like we have to do more alt enter import the class and instead of using the text view i'm going to put in a toast and i'm going to say something like a problem occurred or error all right so then we get to the end so this request object is all bundled up from line 49 to 60. and then once we're done it doesn't actually occur until we add it to this queue so what's the queue and where did where did we assign that so the queue was assigned up here a request queue and then we added the request to the queue so that means we could add more than one request and it will take them in sequential order and then we're done we're going to have another text so let's uh let's just comment that out i don't want to see that all i care to see is what was given back from our london query okay let's cross our fingers and run the app again all right the app's up and running and so it doesn't matter what we type in here remember we're hard coding the word london in here so let's choose get city id and look at there let's hide that keyboard and try it again here is our here's our response it says title london let's look at that again all of that is the same thing that came through from our code here so it says title london location type city let's run it again compare the two side by side you can see that they are the same thing so this is formatted nicely and this is just a straight old text but the concept is there now we're going to change some of the code here and we're going to make this into a json object so you can see that there are two different types of brackets here this is the curly bracket this is a json object and this is the square bracket which means this is a json array so what we want to do is get a json array object just because that's the type of data that's printed on the screen if we were to look at a different one of these requests such as one of these down below here let's get london and let's look at the data you can see that the first character in the json is a curly bracket so this would be a json object that we're trying to to collect and then inside that json object you can see that there is a new array and that array contains like six or seven different days of weather so two different types of json data that we're looking at here either a json object or json array so let's go back to where we were which was this london query and we are going to be looking for a json array object so let's go back into the code and modify a little bit all right so i'm going to probably delete all of this here and uh let's comment it out first of all so put in a control forward slash to put a comment from everybody all right i'm going to type in a capital j now look what we have for options what i want are one of these two right here so json object requests that's if you were expecting to get a json object in this case though we're expecting a json array so i'm going to choose json array request i'm going to call it request and just like i had before i'm going to use the same model so you can see that the the text here is a good pattern to follow so we're going to have a new and this time i'm going to have json array request what are the things that we're going to fill in for the parameters so the first parameter we need is request.method.get so let's just type in the request dot method let's see capital m and then get so that's the type of request so in in apis you can have gets posts deletes puts and updates those those are all things that are that are different types so get and post are the obviously the most common ones if you've seen those in any kind of programming before okay so the next item is the url so the url is the string that's above us so i'm going to just retype url and now the the next part is the response so i'm going to type in a new and then the word response and i'm looking for a response listener so i'm going to type in response listener and what kind of item am i supposed to put between these brackets you can see before it was expecting a string well i'm expecting now a json array so let's type in json array all right so you can see that we now have a semicolon at the end and i'm supposed to have more code to help me out here so let's uh let's go down to this helpful hint that says implement methods so listener is going to have a two two items it's supposed to be a response with a success and also down here a error so let's see if that'll generate that for us i'm going to choose implement methods and sure enough there is a response so let's click ok all right so the first one was created for us okay so it generated the first results okay but i think what we need is another result which is on failure so let's put in a comma right before the end and let's put in the word new response and i want to do a response error listener there we go and the error listener needs to have its methods man i wish this would give me some more type ahead automatically but i'm going to go through the steps one at a time all right so i've got myself what looks a lot like the previous code that we coded but we've got an error so let's uh hover and see what the problem is okay it says here in your json request it says i cannot resolve the constructor so the constructor is obviously missing a parameter that's what a constructor does it takes all the parameters and creates an object so i've got get url and the request listener so something's different than what it's expecting i'm not sure what it is so let's go look at the documentation and find out so i'm going to switch back into my code now i did a simple request and let's let's take a look here at the what's called the standard request so a standard request instead of using a string request like we did before we're going to use a json object and let's scroll down here it says here's what you need to do your json this one's called an object request we did the array request almost the same and look at the look at the parameters here so the first parameter is get that's what we have url then there's something called null i actually don't remember what null is for and then the rest of it is what kind of a thing that you're actually trying to request so null is probably some kind of a parameter that maybe if i read the instructions more closely it would tell me but i don't see it in here but i'm i'm going to take the word for it and put the word null in okay so let's go look here and put in null and now it looks good so the parameter was called json requests no i'd have to go look at more details to know what that was anyway the problem seems to have disappeared now we can go to the response and add something now so let's put in a toast so i put in a toast create a new one and what i'm interested is is to know what comes back from the response so let's uh let's take the word response then and instead of the text here let's paste it it doesn't like that so the response is not a string it's a it's something called a json array so we can just turn it into a string with a two string method and that's good okay for the next item the error listener let's put in a toast again and let's put in a message that says something wrong all right so we've changed our data from a string request to a json array request and let's let's hopefully make this work okay down at the bottom this turned red i'm just going to cut that out and move it up to the top here so why doesn't it like string requests our request was called something else it's called here it's request so let's just copy this and put it over top okay all ever is gone let's see what happens okay so the app's gonna run here and before it gets started i'm gonna switch over to the data that we are expecting this this screen here and uh let's put in get city id there it is so that was the same text that we have listed here and you can see if you look carefully it starts with a little square bracket so we've got ourselves the get city id so we can do better than just getting the entire json array i mean the string did that the advantage of using json data is that you can split it up into pieces so what i want to do first is get the entire array and then get one piece of that array so let's go with this so i want to get a the first item in the array so this is a json object and we're going to call it city info and it's going to be from the response so the response is going to be the get json object and you can see that it's expecting an index so the first item in the list so the first item in the list is the as obviously it's an array of one item so item zero is the first item now we got an error it says uh you have an exception that needs to be handled because you're not guaranteed to actually get valid data so let's surround it with a try catch okay so we're going to try and do this and if something goes wrong we'll print the error all right so now when we're done we should be able to get get the actual json object well i'm not interested in the json object let's look at it again the information that i'm looking at is this this is the key that i'm looking in this is the target so w-o-e-i-d so i got the object which is this item now i need the key value which is w-o-e-i-d so let's let's copy him and we'll bring him to the four so let's go to the next line so we got the json object now i want a string and i'm going to call this thing the city id and so we're going to do the city info dot get string and now i'm going to paste in the name of the string isn't that cool so if that string exists this try catch will succeed and we will have a new string called city id so that's the target that we're looking for on this function so we're going to call it city id equals and then i'm going to type in city id oops let's try that again city id okay so now i won't let me use city id in two places all right so you're getting to see all the errors that are coding as they as they occur so it says i can't figure out what city id is that's because we declared city id inside the try catch and as soon as we left tri-catch the scope of that variable is now gone so what i have to do is define city id further out so let's go and put it right above the try and let's say by default it's an empty string and i don't need to redeclare it and then down here it works okay so we're going to have city ids defined then it's redefined as whatever comes from the value and then we print it here all right let's see if that works we've gone a long ways we're going to run this i'm going to bring up the web page so we can see the id that we're expecting and then finally what happens here so i click here the city id is 44418 beautiful all right does that work for all cities let's go and check so instead of london let's change the url now so let's put in a new city so i'm going to put in phoenix and save it relaunch the app and away we go let's uh let's come over to here and instead of london i'm going to type in phoenix so the id number is now this one 247 1390. let's see if we get the same results over here so i'm going to choose get id and there it is 247 1390. okay so it seems to be getting the id number correctly now i would like to be able to put in the city name here and then get the id so that's the final step that we're trying to get to there's been a long video but i'm showing you all the steps that go into trying to figure out the the code and the documentation so the query let's just take off the city name and now in the url we're going to add to it a new value so let's go with plus and let's get the value from the data input field get text and then i'm going to change that to a tostring method so now we should see whatever value here is attached to the query one more run data that we're expecting and then the app shows up here so now if i type in the word phoenix and let's get rid of the keyboard choose get city id we see 247 1390. let's try somebody else let's try miami everyone wants to know what the weather in miami is so let's check that out there's this the ideas245022 let's go and see what miami brings up on our app miami i assume that's florida and what do we get we got an id number they seem to be working so test this out with various cities now the reason why we did this one first is because we're going to then get the weather report by that city id and so that'll be the next phase of our video here so this is a great stopping point we've got ourselves one item from our list and that is an important id number hi welcome to another video in our weather app in this video we're going to do some refactoring so in this current state we have a lot of code inside a button it's kind of uh complex and we're going to have to make more buttons and so the code will get longer so we're going to try to do some refactoring to make this actually a little bit more well designed [Music] so i'm going to go to the documentation that we were looking at here so this was google's page we skipped over a section called request queue we're going to go back to that down here it says use a singleton pattern so the singleton pattern is common to lots of things in not just java but all applications and a singleton is a class that can only be instantiated a single time one time so the name singleton and all singletons are pretty much coded the same way if you haven't seen one this is a great introduction to why they're important so first of all what do we care about for singleton and why do we only need one instance let's go look at our code here and figure out where this would be so the line that's important to us in this singleton lesson is on line 50. so we're creating a cue called a request queue and then at the end of the code here we are adding a new request so if you were to click the button multiple times it would multiply put in requests and each request as you can see takes a few seconds now we don't want to have multiple cues running in our program one queue is good we just can only handle so much network traffic and so the idea of a singleton says we're going to make a single class that will be listening for button clicks anywhere in our application and it'll handle them in the order that they're given so that's where we're going with this refactoring all right so we're going to take their code that they've given us here and copy and paste it and then modify it a little bit to match our program there's a few things here that we don't need but we will delete them so let's go ahead and we're going to click we're going to create a class called my singleton but before we do that i'm just going to copy here and it copies the entire gray box and then we're going to make a new class called my singleton so let's go back into the project here right click in the java area and we'll call it my singleton now we're going to rename that later to something like data service signal singleton or the request single content okay so we got ourselves the code i'm going to overwrite it so i'm going to delete that and paste and we've got ourselves all of the code here so request queue is the important part we're going to have to import some things here so let's do import the class let's see i'll try alt enter image loader now we're not going to use the image loader so i'm going to get rid of him context is important so we'll do alt enter again all right so the next section down here is called image loader so i'm going to just come down to this line here where it's got image loader don't delete this curly let's just delete the image loader part and let's see a couple more lines will be gone now we have we have a constructor it looks like so the constructor is important because it sets up a uh the ability for only one of these classes to exist so it'll take a parameter called context and then the request queue is the important part says when you're going to create the the this singleton it's going to create one version of the request queue okay then the next part is the singleton classic setup so all languages would probably use singletons this way there's a there's a variable called instance the instance is does this thing exist already has there been a version of this program or this module is it in the memory and this is a check to see if the instance is null means it hasn't been instantiated yet then we're going to make a new instance and if it is already existing then we will just return the one that's already there so this is the key part this is what a singleton does it only allows one instance of the class to be instantiated created all right so now let's go look at the uh the rest of it so the get request queue is important it says if the request you doesn't exist then we're going to invent it or we're going to make it come into a bean so let's use volley again do an import and then down here the request looks like that needs to be imported and then image loader we're going to take out so whatever the image loader was for we don't care now we've got ourselves an entire singleton and there's no errors okay so this is this is the way to handle the cue let's go back into here and so i'm going to comment out the existing queue and we're going to create a new one let's go look at the documentation to see how to do that okay so we're back to this page here that shows us how to do this code and now it says here if you're going to make a request queue we can do it two ways we can get the queue or we can simply add the cue right now so let's uh let's just use this line this one's simpler so i'm going to copy and let's go back to our code so i don't want to instantiate it up here instead i'm going to come down here and delete the line that was there and let's uh let's put in instead of string requests what was the name of the request it's called right up here it's just called request so request all right so the problem here is what kind of a context are we supposed to send so we need to put in the word main activity dot this so this is where it's being run all right so we've got ourselves pretty much the same kind of code i'm going to delete the original not a lot of changes in main activity but the singleton gives us the ability to manage this through central locations so let's delete all the stuff that we had before clean it up a bit and hopefully i haven't wrecked anything i've just done some refactoring to use the what the documentation is recommending so let's run the app so let's see i'll bring up the bring up the weather miami and let's make sure that this is still working so we'll get the same code here if i type in miami miami and then the button and look at there it worked by the way what happens if you don't put in something so if i put in a a city that doesn't exist does it do anything and it says city id is blank so it just gets nothing all right so it doesn't crash but i don't get any value either so that was a refactoring lesson so we did this singleton request and now if we were to have multiple things happening at the same time the singleton will handle them in sequential order hey welcome to part five of our video on weather api app so we're going to turn this code that you see here into a more componentized or modularized type of a refactoring so instead of having a button that has a lot of code inside of it we're going to have a button with a little bit of code and then an external class with some helper code to go with it so we're refactoring here to make our design better [Music] okay so let's get started on this refactoring part we're going to create a separate class that will handle all of the items that are currently listed in the highlighted section so what i want to do is make a class and put it in the java class area so i think a good name for this service is weather data service it's sort of a database access object but it's really for online so the first thing i want to do is define the types of methods that this class will provide so the first one here is going to be return a string called city id so we are going to get the city name and then go through the api process and return a string which will be the city's id so all the code that we did in the previous videos will be reproduced here or copied and pasted here and then refactored we've also got two other things that are in the future so i'm going to put them in now even though they're not quite quite defined properly so the list that we're going to get for the weather report is going to be a list of type weather report models so a model is a class that's going to contain things like the city name the high temperature the low temperature the forecast description and other items that we'll find in our data service and so we're going to have two options for this we can provide an id for the city and then get the weather report and then i'm going to refactor that one to have a simpler method called get the city forecast using the name or by name and so it'll translate a name of a city directly into a forecast and so that's what's ahead of us now as you can see the last two methods here don't have some things defined that we need to define so i'm going to simply comment these out for now and just leave that as things that we're going to have to do in the future so we're going to encounter some problems but we are going to get this one here called city id working so we're going to return a value hopefully with a string now the return part is going to be tricky because this is not going to work like i expect but i'm going to show you the process of learning so that way you can figure out some of the required work arounds that are ahead of us so the first thing i'm going to do is an attempt to copy and paste all of the code that's inside of the button click and then we're going to reproduce it inside of the other class so let's see i've got to get this highlighted correctly i'm going to cut this out and then we're going to replace it in the weather service so let's go ahead and paste everything here as soon as i paste it says wow you've got a lot of things that you're working on for dependencies let's click ok and import all those classes let's start at the very first line so we've got this string url and then it depends on a text item and so we don't have a reference to the the edit text item so we're gonna first of all delete this and change it to a parameter so we're gonna call this thing city name and so you can see that city name is being passed in as a parameter so that's good so let's just uh see what we would do if we were to use this right now so the goal here is to get the city id number and it's going to come from our new class called weather data service dot get city id and then we're going to provide the string which is from our edit text data input get text to string so this here has got some issues we've got a problem here that says get city id doesn't work so so really rather than just talk about the class itself i need to make an instance of it so let's copy and paste that and we'll call it a lower case thing and we're going to have a new weather service weather data service and then for here we put in the lowercase and everything's good so the instance is created and now we uh can get to the methods so so far so this makes this makes sense uh it's not going to work yet there's still problems ahead but this is the goal that i would like to do is a normal java class so let's start with this first line here we've got a string here that's encoded right into our in into our method so i'm going to make this an extraction so let's see if we can refract refactor extract into a constant so here's a trick that you can do and it puts this constant name in there that's kind of a long name let's just call it uh query for city id i like that and let's press enter okay so now you can see the new constant declaration is here so it's a public static final string and then it just copies that string up there so it's just replacing one string with another so the constant is got capital letters by by a convention and then if we have to use that again we don't have to use a second copy of the actual string so it's a good idea to have one source of truth all right for now let's let's keep going down so we're going to do a new request we're going to do a response query and then we come down to a problem here so we've got an issue this was the context of main activity well we don't have main activity anymore this is no longer accessible so what we want to do is have a value of the con of the context here is part of our our class values so let's let's come up here and put in something called context and i'll make a lowercase context let's import the class now how am i going to assign that that's going to come in the form of a constructor so let's make a generate a constructor here so let's go to generate constructor and you can see it says you've got a member variable called context and let's make that a very a parameter that we pass in and then we'll assign it here so this constructor is going to modify something back in mainactivity so what did we do in main activity we created a weather data service and you can see now it says you're missing a parameter well we can get that mainactivity.this is the context so we're sending our context of main activity back to here all right so since we now have a member variable we'll just put in the word context down here all right so does this all work let's see not quite we've got another issue let's change this to context as well and finally the last one all right so now we've got everything uh fixed up here but we've got one error at the end what's what's it say here it says you've created a return type of string and you're there's no return here so we want to return this the city id so this is where we're going to have problems if i type in city id we are going to have issues and it's not just the fact that it's out of scope this literally will not work and we're going to have to create what's called a callback but we'll get to that we'll demonstrate first that it doesn't work so what's the matter here city id where was it defined it was defined up here inside of this uh response so i would like to change this as well so i'm going to move this to a higher scope i'm going to cut copy this and let's let's just put it up here as a member variable and then down in here we're going to take out the string definition so now the scope says we have a city id here it's referenced here it's referenced here and then hopefully returned here so it's not going to return it but we should be able to at least get the same kind of a toast message that we did before okay so back to here notice how short then our code is so our string is going to come back from the data service and let's try toast to see if it actually works so i'm going to say returned and i d of and then we're going to have the city id so hopefully we're going to get the response from the weather data service and then redisplay it here so there's going to be two toasts this toast here is the second one inside here was the first so when we first get the city id from the api it'll toast it here or something wrong one of those two will happen and then finally we'll get here now i believe that this is going to come out as empty it won't work and then we'll have to solve that problem but let's test it we're going to run here and let's go get ourselves to the data that we're expecting let's try miami again and run the app okay so here we are let's type miami and hide the keyboard so the first toast will come from inside the program so the city id equals that and we got we got a quick message there that said returned a null did you see that i'm going to show it again it says no but then city id equals a number so one of the toasts got the id the other one does not let's go check it out where was that so the one that said returned an id of null was here so i'm going to put in here this didn't return anything why not that's kind of unfortunate i told it to return something but it didn't however inside of the weather data service it actually showed me a city id so i'm going to say this worked but it didn't return okay so the comments here show me that this part works and it didn't return it to the uh to the main activity okay so how are we going to solve this problem so we have just uh introduced ourselves to an asynchronous issue what has what is happening is that the first toast shows that there's a null value getting returned it like immediately skipped down to return id and all of this process was kind of like left in the dirt it was left in the dust it skipped over it that's because we are running a background process uh the volley library automatically puts in a cue kind of a background request because it takes a little while for an api to return some data a couple of seconds that's all it takes but we're not going to wait around and freeze up the app and make the user wait we don't want to make things run on what's called the the ui thread which is the user interface thread so we put it this we put this process in the background and we just kind of let it go and it takes its time because we know it's er slow the unfortunate result is that the city id doesn't get assigned anything while this is in the in the process so by the time we get to this line you know we've skipped over and we never came back to wait for it so the the solution here one of the solutions that we can use it's called the callback so let's let's see if we can get a callback to work correctly call back is a way to notify the program that when this process is finished run another method so you can take your time but when you're finished i will be here waiting so that's what a callback is now in most languages there's some things that have gone beyond callbacks so callbacks get messy they start to get nested brackets until you get two three four levels deep and you lose track of your parentheses and so that's called callback hell if you get too deep and so unfortunately developing apps in android and java with callbacks is still working in that method other languages such as javascript and c-sharp and things like that have async and a weight for a newer way to manage things so there's probably ways to do async and await with libraries in java but i'm just going to show you the callback method because it's built right into the language so let's go look in some google queries about how to do this so i'm looking for the phrase android callback with volley now you'd expect the first thing to come up would be a documentation from google's developer tutorials and i scroll through here and i i'm not seeing it so there is something in here but this is not about uh volley i looked at that one so i'm going to just go with my stack overflow friends here and see what this does now i already checked in here and i know that there is a good explanation for how we're trying to handle this so i'm coming down to the first answer here it says there are three answers for this guy's problem and this is this is a good code to follow so it works uh i tested it out so here is here's the guy's issue he is using a json object request very similar to ours we're using a json array request but the principle applies and what he did then is he first of all defined a volley response listener so this here is some code that we're just going to copy and we're going to paste it right into our example and then make a little tweak here that like he did okay so the first thing that i'm going to do up here is before my actual event i'm going to put in this interface a volley response listener so you can see that the the goal here for this response listener is to have two different methods one's called on error and it's going to have a string message and the other one is an object response so what kind of response are we expecting out of this thing so out of our our response here we are pretty much getting the city id the city id in this case is a string so for my return type here i'm going to change this to a string and i'm going to call it actually city id just so i know what i'm expecting to come back so the volley response listener is specific to this method for right now so now i'm going to insert this response listener into my parameters here so let's look at the the calling definition here so i'm expecting one parameter but i'm going to add a second one all right so this one here i'm going to put in as a volley response listener so remember volley is the library we're working with and then when we get back to main activity we can implement these two methods called on error and on response now before we get to the response we need to actually make it happen so come down into my code to where the comment said this worked this is where we know that the city id has a valid number in it so we are going to use the volley response listener and we have two choices we have on response and on error see that's the two first two items here those are the exact same names as were defined up in this interface so we're going to choose on response and then provide the city id as the value that's coming back to the main main activity now let's uh also put in the error so we're going to do the same process here we're going to put in a volley response listener dot and this time on error and we'll say something wrong that's what's going to come back instead of a city id it's going to return something wrong okay so this is the key to link the correct values to our main activity as a matter of fact since this was useless this return i'm going to comment it out and i'm going to change the return type from string to void it doesn't seem to work doesn't work actually so we don't even need it but this response listener is going to help us so back to main activity we got to add a new item see we got a red line it says your weather data service get id has now two parameters the second parameter is a new we're going to call it new volley response listener look at there so you can see it's giving some type of head help i'm going to press enter and beautiful it now implements two different methods for us on error and on response so we are going to take the toast message cut that out and put it inside of our response and instead see city id is coming out here city id and then we're going to put another message in here and just say text is that something's wrong something wrong okay i put a comma and what do we got we got an error still all right so the error says you have expected the weather data service to return a string oh okay i'm going to delete that part we didn't actually uh implement that anymore okay so now careful let's make sure we got everything right here now the get city id method is going to have this link called the response listener which gives us an error message or response message and one of those two should come out so that is a callback let's see if a callback actually works so i want to remove the toast from inside of the data service so nothing more from there that's just getting the data and the toasts now that are exist are here and here okay let's run this okay let's switch back into the weather id and get the app up and running and let's see if we can get a valid id to text out in front of us so let's go to miami again and remove the keyboard and choose get city id okay it says it returned a value it seems to be working let's try london and let's minimize the keyboard and choose get the id looks like we got four four four one eight so the process of doing a callback is a little complex it's a little awkward but it works so we have now successfully created a weather data service and it has the method called get city id and we found out that we if we actually want to get that value we can't just return it as a string we have to wait for it so we use a callback method all right one final refactoring is this here is going to be used in the other buttons so there's no sense in creating a new one each time i click a button so i'm going to cut this and move it up and so it now sits at the class level and now what's the problem here it says it must be declared as final let's let's just put as final there and so now it should be working okay so the next video we're going to do is we're going to take this nice pattern that we've developed here and apply it to the other two buttons and so that's just ahead hi welcome back to another video in our weather app we're using an api service as you can see on the left side and we're trying to get the api to display a weather report over on the right side so we're going to create this button here called give me a weather report by id that'll be coming right up [Music] so in the previous videos we were able to get just the id of the london uh city as four four four one eight now we want to take this four four four one eight and put it into our input field and then choose this button called get weather by id and that will produce a weather report and then in a future video we're going to take the word london and then go for get weather by name but in the intermediate we're going to just be happy if we can get it by the id number so that's what's coming next all right so let's go and take a look at the code and see where we're going to go with that so this here right now is the button click listener and all it does is tell me a toast that says you clicked me too so we want to get rid of that and change it to some real code now we're going to use this weather service id so let's copy and paste all of this code here and hopefully just not have to do a whole lot of changes to it so i'm going to copy him and paste him down here so we obviously don't want to do get city id we want to get weather by id i think that is the method that's coming up so let's double check here we commented it out and let's see this was called get forecast by id i'm sorry let's comment this back in and i'm going to use get forecast by id as my next item all right and then there's a bunch of junk that's not working yet because this obviously has not been coded let's come back and fix these errors but first of all we have to make sure that our weather service is working so what is the first error it says i promised it that we would be using a list of weather report model well that's that's true but we don't have one of these called the weather report model yet so let's uh cut this out and put it into here and call this report and we're going to make it a new list and let's see we can't use list it's going to be array lists there and we have to import array lists okay now here's the issue with weather report model the weather report model is supposed to be a class that saves a whole bunch of data fields and we haven't defined it yet so let's create it and it's going to be in this package right here and click ok there it is so we have a weather report model now what kind of properties does it need well to answer that question we have to go look at the data that's been provided to us so i'm going to go back to my api and let's back up a few until we get down to one of these so we're going to do a re forecast so the forecast is going to look like this it's going to have all these properties in it so i could probably just copy one of these and start using my weather model based on the names here so let's just copy that and let's paste it here and i'm going to use that as a starting point so using the list of properties that i got from the api i am going to create all the properties that will go into this object called the weather report model so each one of them has its own data property so you can see that the int for id matches the type that's listed in the strings above so it's an int now most of these are strings so the weather state name the weather state abbreviation and the wind direction compass the created date all of these are strings now some of these are decimals so i'm going to use the word float as the property for the number and so we got floats for the max temperature the temp the min temperature the wind speed the wind direction the air pressure doesn't have a decimal point so it looks like that's an integer humidity also is an integer visibility we go back to float and predictability looks like an integer so i'm making estimations on which of these properties apply but things with a decimal point get floats and things that don't have decimal points are ins all right so we've got all these properties now created i can now just delete all of this helper code that i had put in earlier now what should we do with the rest of this we've got the properties we need some extra helpers so let's make a constructor first of all so let's go to generate a constructor and let's select all of the properties and click ok and there's a lot of properties but fortunately they're all defined for us that saves a lot of typing we need getters and setters for all these guys so let's do a generate and do getters and setters and let's select everybody okay now there's one other thing that we're going to use later it's the two string method so let's uh let's define one of these maybe at the let's see probably should go right here let's define the tostring method we can define that using generate as well and let's see tostring now i'm going to click ok and select all of these it's going to create one really long string we're probably going to come back and eliminate some of these later because this is a lot of information but for right now that's a good valid tostring method okay so that defines a weather report model so how are we going to make that work let's see we've got ourselves a list problem and we need to make this thing void i'm getting rid of all these errors so we have now defined ourselves the weather report model and we know that it's going to be a list of we're going to call it report so now the next goal is to untangle this rest service data and we want to be able to assign each one of these properties into one of the values of our weather report model so let's first of all figure out what kind of request we're going to ask for this very first line here has a curly bracket so that indicates that this is a json object the first property of a json object is called consolidated weather that's the property and this happens to be a list or an array we'll call it so we'll collapse this and we can see that each item each item in our list has 15 properties and that's the end of the list so how many items are there it looks like one two three four five six so there's a six day forecast you notice that so that the first day shows today's current date which is may 25th and then let's open the second item in the list and you can see that that date is may 26th and i bet you 27th is coming up next let's check and sure enough so this is a forecast for the next six days for the city of london now we're going to only be interested in this property called consolidated weather we are expecting an array so this is two requests that we're going to have to get we're going to have to get the object the first object and then the property of that object is an array so let's see how this will go all right so now let's let's attack the problem here so we know that we're expecting to get a an object and then we're going to get an array all right so let's pencil out what we're going to do because we need a road map this is getting a little complex so the first thing we need to do is get the json object from the request and then we know that the item in that json object is called the consolidated weather which is an array and then each item in that array is an object that is going to give us all the properties of a weather report so it will become a new object called weather report model so that's where we're going so first of all let's get the json object and then we can start from there so let's uh let's take a look at what we did up here so we have a request that looks like like this here so i'm going to start with a json array request and modify it so let's just copy the first line and since we are looking for an object i'm going to modify here so instead of json array request it's supposed to be a json object request and let's modify this so json object request and the results are going to be a json object not a json array okay we're going to put a close bracket there so what's the problem it says we're going to have an issue that says you probably haven't implemented your methods so let's choose that and we want the on response so that comes out and it says we are expecting a response of a json object so compared to what we had before this was a json array response so we got one of each all right so we got an issue with the url so the url is undefined and let's let's fix the url so earlier we created a constant for the url up here we're going to make a new constant so let's copy and paste this one and let's call this thing query for city weather by id and then we're going to delete this and replace it with whatever comes from the documentation so the the uh the url that we're looking for it looks like this up here so i'm going to copy and paste from the address bar so that's going to come into our new constant now the value here is the city's id so 44418 as i recall was from london so i'm going to just take that out and one of the slashes so the url now needs to have a definition so let's type in a string here and call it url and that's going to be the query for city by weather id and then we're going to have a plus and we need to define it as an addition to this value here the city id so concatenate those two together and you get yourself a url okay what do we got going here this it's is to have no parentheses there okay so this is looking like pretty good we got ourselves uh the jason response all right so we've got ourselves the uh response now up above here you notice we had this error listener thing and we haven't implemented that down here so let's add that we're going to put in a comma and put in a new uh what's it called response error listener and that's the first suggestion so i'll just press enter and we still have something left over here we need to close off this parentheses and then a semicolon okay so all these callbacks really are difficult to keep track of that's why people are trying to get away from so many nested events like this but we've got ourselves a looks like an event here that might be successful we're going to at least get the consolidated weather now from the uh the property in here so let's uh let's check this out we can probably get it so let's make a toast for right now just to test it out and we are going to do the response dot to string and i'm going to ignore the error part and let's see what happens this isn't complete but we can at least test it come back into our main activity uh what did we do wrong here okay yeah so this was i'm going to just uh delete that and try again so i'm going to try a weather data service dot get forecast by id and we're going to just put in the string 44418 because we know that is london okay so that's simpler to test than what i was trying to do earlier let's see if it works i'm going to run the app all right so the app starts starting to start up i'm going to come back into here so what we're expecting is we're going to get a long list of items and let's see what happens so come on app we're ready to go and i don't have to put anything in here i've got 44418 as my default id and nothing nothing nothing at all okay so i forgot something obviously let's go check it out and i think i know what it is so in the data weather service i created a request now what's supposed to happen to that request after it was made does it automatically run no it doesn't so just just like up here i have this get instance and add the request to the queue i need to do that as well down at the bottom here so i'm going to expect that to be the last thing i do and rerun the app okay so you're getting to see how troubleshooting happens you're probably going to commit the same errors that i'm making so it's good to see the solutions as well as just a good code okay we running yet here we go let's check the weather by id and anything whoa look at that we had a toast of a quite a lot of text so that to me looks like consolidated weather it's showing all of the items that are in there so that's it's producing the data we expect but we're still not there so i think maybe in the next video i'm going to show you how to make a single request show only today's date because i really don't want to show the entire forecast for the week that's a little overwhelming so we'll do that next hey welcome back to our weather app we're using api services from a weather service and we're making an android application so if you're just joining us go back and check out some of the previous videos in this video we're going to actually convert from this horrible looking toast as you can see coming up here it's got a lot of text so this huge thing in this text is going to be changed into a list that shows up in our list view so that's where we're going [Music] all right so let's uh let's see if we can tame this thing so we're trying to get the weather by id and we've got this long list of data we're going to modify our request here so we're into this weather data service class and up until now we've been able to get the uh the string here for the response so this response here gave us the entire json object now i'm interested in just the first item which is the the class called the consolidated weather so what i'm going to do is just pick out one of those things from the object and it's we know it's a list of json things json object things so i'm going to define a list of json object and i'm going to call it exactly the property that was in the api it's called consolidated weather list now to get that i'm going to have to go to the response and i want to get a what get a json something sure enough there is one that we can pick from called the json array and the name of that is called consolidated weather so hopefully that works now the hopefully part is where the computer says no you're not going to just hope for it you have to surround this with a try catch because if it doesn't work i'm going to produce an error all right so now what do we got okay so it didn't convert well here so the problem is that it says you are requiring a list and i found a json array well maybe we can do this we can just change this to a json array type so let's go json array is that in there json array okay good so now i've got the right data types i've got json array coming here and the type that we're getting is a json array beautiful now i only care about uh each item individually so we're going to go loop through this and pull it out but before we do the loop let's just pull out the first item all right so what i'd like to do is create a new instance of the weather report model remember that model that has all the properties and so i'm going to just say hey make me a new one now i've got an error that says you can't make me a new one unless you provide me with all of these properties oh my goodness that's a long constructor well it could be done and uh it would be one long line so i'm going to cheat i'm going to make another constructor that has no parameters so let's go back to the weather report model and i'm going to generate another constructor so slip it in right here below the first constructor generate a constructor and this time i'm going to not select anything so let's see just select the first item and there it is this isn't a null constructor or an empty constructor let's see if that will work now so now it's happy it says you can create basically an empty weather report model and then one by one i'm going to fill those items in so i need to know the list of all of those items so uh wow this is a lot so i might also just copy the list here and i'm going to dump it in right in this section even though it's going to cause some errors it's going to say hey i have no idea what those properties are all right so now i need an object that i can pull all these properties off of so i have so far been able to get the json object response and then i was able to get the consolidated weather list so i know that the first item in the consolidated weather list is a is a json object so let's do that let's go json object and we'll call this thing first day from api and he is going to be the consolidated weather list and we're going to get item zero okay did it work so i know that i'm supposed to get the first item out of the list and it's going to be a json object but it isn't guaranteed to be a json object so it says do you want to cast this if i put in the cast it says i'm going to convert this into a json object i think that'll work because in my in my service the first item let's take a check again this is definitely the first item in the list is a json object so the cast should have no problem at all all right so now how are we going to get all of these properties so i'm trying to get first a to get a bunch of properties so let's do first day dot set and the first property is that i'm going to set is the id now we're going to get the id what's going to come from the first day from the api dot get and i'm going to choose the get item and its value is id okay this is going to take a while so just watch me type all right so this next process is quite tedious we have to go and get all of the properties from the first day from api object and we're going to assign those to one of the properties in our model which is called first day that's the instance so you can see i'm going to say we're going to set the id and we're going to get it from the integer called id in our api and then they're going to set the weather state name which is also from weather state name so we're going to get these as mostly strings so it's get string get string get string get string however when we get down to the set min temperature we are going to encounter a float and it doesn't have an option apparently to get a float so you could use probably get double or get long either one of those and it will correctly parse the value which is a decimal number and then we're going to assign it to our property which is a float so java does allow you to cast a double or a long into a float now when we're all done here we're going to have all the properties with the correct spelling so make sure that they're all spelled exactly right if they're one of them spelled wrong it'll crash and we'll find the error but it's better not to have that error of course now since i've got all of these things typed in now and hopefully you do too i'm going to then delete all of these different properties that came from the class and when we're done we're going to have first day as the proper thing that's going to be returned so to return it that's the catch we need to come up with another uh return type so let's go and look at the volley response listener i'm going to copy that and i'm going to now use it in the next item so i'm going to create another interface and so the response listener now for the forecast so we're going to call this thing maybe a forecast forecast by id response and that is what's going to come down as my reti time to return so instead of returning a string i'm expecting it to return a single value called a weather report model and let's just put him in there as the return type that we're going to hopefully play with at the end let's see we have to tell it that we're going to expect this so we're going to put in here the forecast response let's see for cast by id response and let's see forecast by id response very good and now here we can do forecast by id response dot on response we're going to send back our first day man that was a lot of work to get to there but this will hopefully return it to our main activity okay so the goal here is to uh send this uh first day response back uh let's check a few of things up here so here is a toast that responds it sends the entire object so i'm going to just comment that out we don't need him anymore that was for testing let's go to the main activity and we need to now put in the response listener so that's a new forecast there it is response so let's uh check to see if we on the response here i want to do a toast here and i want to bring back the what was the object there it's called weather report model let's see weather report model and we're going to do a two string so for lucky we're going to get a weather report and if we're not so lucky we'll put an error in so let's put in a toast here and we'll say something wrong here and we'll have to figure out what that is in the error logs let's let's run it and see what happens so i started up here and run and let's try get weather by id and looks like i get nothing so something didn't go well so i'm going to come back into the code here i'm going to switch to logcat let's see where the log header there it is and we've got an issue line number 89 and 83 and here is a message no value for consol consolidated so i spelled this wrong let's let's fix that let's see click on line 89 there it is line 89 which is this here so consolidated weather i obviously spelled wrong let's uh let's copy consolidated weather from the code right there and over over write my spelling error okay let's try again okay rerun and try it again okay so all of this here it is get weather by id and we got a toast that shows all of the properties of that weather so that's a lot of stuff but it appears to be working correctly now there's one more thing i'm going to change here before we're done and this city id city id and we hard coded a city id and where was that at so right here we're going to do the city id is not from four four four one eight i'm going to get it from the edit text data input and get the text and change it to a string so now we should be able to get weather for anybody and anyone that the service knows about so let's check it out i'm going to try putting in london and i'm going to try to put in some other names let's see 44418 get the weather by the id and sure enough there it is now i wanted to know what the uh let's try some other city let's go with phoenix again and get the id number oh man i don't remember how to copy that so let's uh let's come back into our api and see if we can get an id number so let's see london let's change that to phoenix so we can get an id number there it is so i'm going to copy this 247 1390 and put it right into my id there see can i paste it no i can't let's try it 2 4 7 1 and nine zero i got that right and what do we have there it is i've got ourselves a number that seems to be valid if i put in an invalid number i'm gonna add a nine what do we get and anything anything at all appears that it doesn't work so it's causing an error anyway if i put in a correct number i've got myself a weather report okay we're getting further along we're going to now create a list of stuff here and we'll show not just the first day but all of the days of the weather but this video is already long enough so we'll save that for the next next up is to create a list of the forecasts hey welcome back to another part for our weather api app in the last video we were able to create a service that would give us the weather id for the first day of the report so you can see that this list here is for phoenix and when i choose get weather by id i get one day so the first thing says light clouds and that's what it says here so what our goal is now is to take the report here and show all of these reports and put them in a list [Music] okay so to create this list we're going to have to modify the type of data that is sent back from our service so let's go look at the service that was created called the weather data service and this thing is supposed to get an entire list and right now it just does something called first day as you can see from our code here this line here says just get me the first day so what i'd like to do now is to get the entire loop of the list of things so first date is rather misleading i'm going to name this as one day so let's do a refactor and rename and i'm going to call this thing one day let's see if i can get it right one day let's call it one day weather all right now instead of zero we're going to do the loop all right so i want to make a for loop that's going to go from zero to the length of the list and remember the length of the list is consolidated weatherlist dot length and then instead of getting just one item we're going to go through all the lists all right so let's do a couple of changes here i have a problem with spelling consolidated weather so i'm going to change this to the word consolidated spelled correctly and then paste over the others okay instead of item zero it should be item i so if you remember up at the top of my class here i have a list already it's called a mod it's called report and so let's let's change that maybe to the word report so i'm going to rename that and let's call it weather report models something plural so we know it's a list now down at the end of the list we're going to add one all right so we're going to add one day weather to the weather report models now when we get to the callback instead of responding with just one item we're going to talk to the entire list okay so that's going to break something it's going to say that your your callback is not designed for a list it was designed for a single item so let's go and change our list up here so our callback is supposed to give us a list of weather report models all right so it's going to do weather report models and then the response here is going to hopefully match with that now let's go back into change in the main activity let's fix it as well here so this is supposed to capture a an entire list of things so let's change this to a list of weather report models and let's call this thing our same idea so weather report models and then we're going to import the class okay so now we have ourselves the list here instead of doing a toast we are going to now include this as part of our list view so we need a layout adapter okay so now we have to create two things first of all we have to create an arrayadapter and then assign that arraylap adapter to the list view so the arrayadapter is a class that contains a few properties first of all the context has to be set so we'll use mainactivity.this for the context and then we're going to dig into a predefined arrayadapter type so type in android.r.layout.simplelist item1 so there are other different types of simple list adapters we can pick but i always go to this one it seems to work fine this is not something that i defined it's something that was pre-defined as something given to us in android the last item in the list is the actual list that's going to be chosen for the values and then we simply set the adapter here into so let's switch back into the consolidated weather page where we can see the actual number come up and i'm going to type in a number here so let's use the exact same number that was given to us so this is a 2 4 7 1 3 9 0 which is phoenix and choose get weather by id and there it is so this is a one item in the list that's two items three so it's not very easy to read but we do have a list let's fix it up so it's easier to read i'm gonna go back and change the model to string so let's go into the model here so the weather report model so let's just fix this up a little bit let's uh get rid of some of these things so like the id we can get that out of the way and let's see the weather state i'm seriously just going to remove most of this stuff here so we'll get the weather state name and then what else do we want let's create i don't really care let's get let's the date is important so let's put in the word um date and a colon and let's see the maximum temperature and let's just go with those so take everybody else out and that shortens things up quite a bit so instead of min i'm going to change it to low for max i'm going to change it to high so i'm shortening things down you can make this say pretty much whatever style you want it's just a string and let's uh let's fix it all right so let's see what that does uh see if it's any better let's run it and uh we'll get a shorter view for each item in the list okay so let's bring this back up again so i can see this number let's type in a number for 2 4 7 one three nine zero and get the weather so i'm getting six different weather reports but they're all showing uh for the day five thirty and so that doesn't seem quite right let's go check it out 5 30. sure enough it says heavy clouds and i don't understand why it's showing just the last one okay coming back into the code here i realized i did something a little bit odd so this here was left over from the previous iteration of my program i created the object and then i started the for loop so i'm going to cut this out and put it inside the for loop so we recreate a new one each time we go through the loop so we create a new object and then at the end we add it so let's see if that helps at all and the weather report model i'm going to fix up a little bit here so the so i'm going to change we don't need to have this listed here like like that let's take that out and let's see if that works any better all right so it looks like this is working better i put in the id number for phoenix and i get the report so it could probably be formatted a little bit better i need a space in here so the two-string method isn't that pretty but it could be improved upon so what we're going to do next then is instead of just showing the number here which is impossible for me to remember except for the one i think was 444 118 which was london and then beyond those two cities i don't remember any of them so for the last video or the last section we're going to have to do is create this button here called weather by name and so we'll put in the name of the city such as london and that will generate the list of data that we have in front of us here instead of trying to remember the city's id number so that's coming up next hey welcome back to another video for our weather api demo in the previous videos we were able to get a list of data from the cities now instead of typing in the city number i'm going to actually be able to create this view by looking at the city name so in this section we're going to modify the function here or the method for get city name right now it just tells me what i typed so let's uh fix that so let's go back into the code here and we are going to add a new item into the report so in a previous video we created a promise down here i'm going to uncomment that promise and here's what we're going to do we're going to change this to void and we are going to get the city forecast if the person gives us the city name so we were able to get the values out of this thing if we were using the id number so that's not very convenient so we're going to have to change this to get the by the city name so here's the strategy we're going to call twice to the api to get our values so the first is we are going to get the city id given the name we were able to do that earlier then we're going to fetch the city forecast if we have the city id so we're basically combining the two functions that we've already created all right so to start off here we're going to call the function called getcityid and we can provide it with the city name because that's given to us in the parameter above here now the response that is given from this function is a volley response listener and so we'll create a new instance of that and so we'll have two different responses to handle one is on error and the other is on response so inside of response we can now claim that we have the city id so that's what this function just got to us now we're going to turn around and call a second function which is get forecast by id this method also has a response it's called forecast by id response so this callback is also going to happen and then when we get to the on response item we have a promise that we can make that says we have the weather report and we can send that back to the main activity so we're starting to see nested callbacks here this is where people start calling it callback hell because we can lose track of the parentheses and brackets very easily it's confusing all right so now we have this claim here that we have the weather report now we have to create another response and a callback to make this work so let's define one at the top here all right so we're going to create the interface that's going to define the callback so i'm just going to use it a name that matches closely to this function call it getcityforecast by name callback and the same two different types of things are promised in here in the interface we're going to have an on error and a non-response the response of course is the important one we want to respond with a list of weather report models now that we have the callback defined we can go add it to our function so we're going to say that we're expecting to see a callback called getcityforecastbynamecallback once that's defined we can come down into our method on the response from the previous callback and call this one so we're going to do get callback and we're going to say on response and we are going to then reply with this thing called weather report models okay that should reply correctly so now let's go back into our main activity and we can probably duplicate a lot of the things that we did from the previous guys so let's just copy and paste and we will modify so we got ourselves here instead of get by id we're going to say get city by name and we're expecting a different reply and so we've got ourselves here the list and i think the weather report models should come back as we expect them to wow that was a lot of code but let's see if it works okay we're up and running so let's put in a city and let's hide the keyboard and choose get by name so hopefully london will now populate a list of items and we're getting nothing so oh it did come up so it just took a little while so why was it so slow well it's slow because we're calling the api twice let's see if it's just as slow if we type in another city and see what happens so that one came up quite a bit faster so they're getting light rain in kansas city and let's see what's going on in lima down there in south america looks to me like it's running so we've got ourselves get by id or get the city ids you can see it shows up and if i try to get the id i have to actually put in the number here so let's put in four four four one eight let's see one more extra four there so we can show london that seems to work and then finally we're able to put in a number or name here so let's try new york and see what the weather is in new york and there it is they have clouds so we've got ourselves a finished app this here is quite complex it shows us how to use the api service shows us how to use callbacks and it shows us how to work with a singleton so several different things that are now new to your toolbox in your java programming kit so please uh leave your comments below to see if there's uh any criticisms or any suggestions which you would have to make this look better so i think the first thing that i would do is instead of using a simple list adapter i would create more of a complex one in the api instructions they're strongly encouraging us to use icons and so if you look back at their page here you can see they've got all these icons that you should probably put into your app and you can show them as pictures instead of just text in your forecast so there's lots of things that you can improve but this is a good start so thanks for watching and if you like the channel go ahead and subscribe and look at some of the other items there's not only android programming here but there's c-sharp there's php a lot of work with databases and computer security so a lot of things to learn here and if you're interested in studying at grand canyon university look us up online and you can see some of these activities are actually taught in the classroom so we'll see you soon
Info
Channel: freeCodeCamp.org
Views: 85,015
Rating: 4.9628339 out of 5
Keywords:
Id: xPi-z3nOcn8
Channel Id: undefined
Length: 135min 20sec (8120 seconds)
Published: Wed Dec 16 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.