Kotlin Youtube - How to Quickly Fetch Parse JSON with OkHttp and Gson (Ep 2)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what is up guys welcome back to the channel and welcome to lesson 2 of the Kotlin series on how to build out the YouTube application on the Android platform so in the last lesson I kind of showed you guys how to construct a ListView component using this thing called a recycler review and so if you found that concept kind of confusing you're probably not too familiar with the idea of a view holder so I've provided a link down below that kind of explains how you put together all of this stuff so make sure to go check that out but anyhow for today's lesson we're going to transform our current list of kind of the hard-coded values for example first title and second and third we're going to transform this into a much more dynamic list which is what you're seeing in the middle and basically this list is powered by a JSON service coming from a REST API and we're going to take all that data and turn it into these views right here in the middle so these are individual rows for our list and this kind of resembles our final product which is over here on the right side and so ABC Instagram firebase here and Instagram firebase there so we need to achieve this screen before we can't get to the final product and surprisingly it's actually very easy to consume JSON data in the Java or a Colin platform so you'll be surprised how few lines it actually takes for us to do all this if you're coming from the iOS or Swift programming world so hope you're ready to code let's get back into Android studio right now all right so let's get started here by going back to our current project and I would like to run my code to make sure our ListView is currently rendering properly instead of our Android emulator on the right side and we have first title second third and the illicit is actually powered by this and main adapter class that we constructed in the very last lesson so make sure to get caught up using the episode 1 link down in the description below and you should be ready for today's episode where we're going to parse out some JSON inside of this main d-class so mainactivity is what you're seeing over here and inside of oncreate is the code that executes when your view finishes loading so now here at let's say fetch JSON as a function that I will create right below so why don't we get some extra lines and down here we will say fu n fetch JSON and then down here we can actually print out some console messages down in this area below which is the logcat and down here we'll just say let's see attempting to fetch JSON all right pretty good message and over here you can hit the run or doesn't control R to run your application again I tend to like using shortcuts because I don't want to reach all the way to the corner to this little tiny button to actually execute my code and so there we go down here we now see attempting to fetch a Sun and one thing I do want to mention is that there's this I over here the capital A and capital W and these are info and warning thresholds for your messages so that's the cool thing about Android if you want to turn off all info messages just go to the warned threshold and you will only see the W and for verbose you see all this garbage and we're not really interested in all that stuff so why don't we just leave it on info for now and we can see our print messages down in the bottom ok so now it's time for the interesting part of today's lesson which is to actually fetch our JSON somehow inside of the Android platform and it's actually very easy to do this but first we need to know where our JSON data is coming from so this URL provides us with this blob of JSON data and I'm using this JSON and view extension which makes it print out very pretty like this over here and I'll provide this link down in the description below so make sure to copy it and you can kind of take a look at what it is comprised of and we have a user up at the very top and then we have a list of videos down below you can kind of see this bracket which means it's an array and we have the video ID and inside of here we also have the channel for which the video belongs due and so all of that data is actually what we see inside of this view so we see the video name which is Instagram firebase and we could be channel which is let's build that app and we have 20k views which is that over there so we're going to consume all this data using a URL request somehow inside of the Kotlin code in the back and the easiest way of doing this is to actually use some third-party libraries to make our lives a lot easier and the first one we will look at is something called okay HTTP which is a URL HTTP client for Android and Java applications and so the way that you would integrate this is to read the documentation first but I don't exactly wants you to read it today so what I'll do is I'll show you how to install the okay HTTP library by modifying our Gradle file with this line of code so let's copy and let me just bring this down to the bottom and we want to go to our bill Gradle file for the module app and down below so here see here is where we see where we integrate third-party libraries and there are you just simply paste the compile line and this library comes from the accompanying square so it's very reliable and you can pretty much trust what it's doing and all you have to do now is hit the sync Now button which installs the HTTP client library inside of your code so that you can use it a little bit later on so you get run after this sink is done everything's going to look the same so why don't we go ahead and use this HTTP client right now inside of fetch JSON okay so how are we going to do this well let me copy this link first and then inside of fetch case I will say Val URL equals this string so eval is the way that you would define a constant that doesn't change and what do we do with URL well let's construct a client first with a constant client and we'll use okay HTTP client like that and we'll use the paren paren to construct a new client and so with the client we can actually make a URL request to actually get the data from this URL endpoint which is kind of like a REST API service and the way you do that is to say new call and this you actually need something called a request so it's a passes and some kind of request object and so why don't we construct the requests up here with a valid request and I believe you construct it with requests like that so make sure to select the okay HTTP 3 version there's a lot more down here so you want that and then you will say dot builder and you would say a parentheses parentheses and then finally you would say URL let's say let's use this string 1 and the URL is obviously the one coming from above and then finally you just need to call them bill so a little bit of code and now you have your request object which you pass the inside of this guy so new call request based in there and then you would have to actually execute your request all right so a lot of new code that you're probably not familiar with and your question that you have right now is where the heck do you come up with all this code right so if you go back to the ok HTTP web site down here you actually get a little bit of documentation as to how you construct your URLs so what I'm actually doing is probably using this over here and oh this is currently in Java syntax so I just converted it to Kotlin kind of on the fly but that's kind of how it works and the common code is a little bit simpler and I find it a little bit easier to use alright so now that you kind of understand how the Catalan language works with this client you have to either execute it or actually in cue it so you can't really execute it because we're actually on mean--you is red right now and Android doesn't let you execute HTTP requests on the main thread so I'm going to use in cue instead and say let's say thank you and the strangest thing about this method call is it requires you to pass in some kind of response callback for whenever your internet connection is finished resolving this request so the way you would actually fill it out over here is this a object which is a keyword so make sure you spell it correctly and you say call back like that from okay HTTP three like that and you just say brace brace and you should be okay now there is a little bit of an error right here so it says that object is not abstract and does not implement abstract member and you need to implement this function called on failure so let's just do that by saying on fail you get that and then the next thing it tells you to you implement is this thing called on response and that's basically when your request is done and this is when you actually get a response all right so this should be pretty straightforward you're pretty much waiting for the response and if your request fails you get notified down here so you'd say something like println you know fail to execute execute request and then up here is actually when your request is done so what do we want to do here well we can say something like print Ln and what do we want to print out well you got to get the body of your response by saying equals response dot body dot string and I don't actually get your body out of your request so this you have to fix it with these optional question marks like that and now you can try to run your code and you will attempt to fetch the JSON that's coming from this URL over here and well as you can see your application just failed to launch and it says down here permission denied and missing Internet permissions and instead of Android applications you have to provide a lot of different types of permissions and the way you do that is to modify your manifest file say Oh Android manifest and you have some things in here that define what your application is called so over here this label right here kind of tells you my application is called Kotlin YouTube LBT a so if you command click in here it actually takes you into this resource file which is value strings this file over here and that's what that is let me go back to the Android manifest and show you how to add a internet permission so you just say permission I think user permission like that and over here you just type in Internet and you'll get this guy's internet and just close it off with a slash and you should be okay to go here so let's run our application one more time and gonna monitor what's happening inside of the logcat thing down here and so you see we have user ID 1 named Brian Brian boom videos I do you want Instagram firebase so that message is being printed out down in the on response section over here you can also put breakpoints which is something that I really like doing so hit the debug over here which is also control D select your emulator and we're going to fire off our request and wait for their breakpoint to be kind of executed here so we got a breakpoint and you see if I hit I think it's f6 or f8 so f8 we hop down one line and you see body is this user thing down here so this is the body and that is exactly what we have inside of our API response which is this over here so you have user you have videos and that's all being printed out down below so you have videos over there and you also have user over there so let's run this or continue and let's see what logcat is printing out and that is a string down there alright so now that we're successful in getting a response back from our JSON service and then storing it into this body string variable we can now convert this entire string into some model objects for our program so that you know we can use it a lot more easily and so model objects typically are just standard classes inside of your program and I'll create this class which I'll call home feed with a couple of properties on it so the home feed is pretty much going to be this entire object which has two properties the user and the videos property which is a list of videos so let me create that really quickly with a constructor so this is my constructor and the properties will be val and user and this is going to be a user type like that and then the other property is val videos which is going to be a list like that hit enter and instead of here you need to construct another class called VM so I don't really want to define this class user just yet so I'll just remove that because we don't display it you know anywhere inside of our application over here so we'll just omit that for now and we'll move on to you constructing this video class over here so the video has ID and also name and all this good stuff so why don't I create ID and name for this video model objects of class the video has two properties Val the ID is a type integer and then the other value or the other property is going to be named before the title of our video which is going to be a string all right so ho feet is going to contain a list of these video objects and we need to somehow convert this body string which is down here into this object so that we can present it inside of our list over here so how do we actually do that well it's actually very easy inside of Kotlin and Java I mean compared to I wasn't Swift this stuff is actually super super easy and we're going to use this library called jisan which comes from the nice old company of google.com and the way that you install this is again you copy the compile line and you added to your Gradle configuration so hopefully all of this is becoming more and more familiar with how to build Android app so go back to your build.gradle file copy and paste that line in there if these sync to download the library into your project and you should be good to go so one question might be what exactly are these number as well as just the version of your library so make sure you are installing the correct versions and you should be okay so I just finished syncing my project together you can run and everything should be ok so let me just go back to you where I am at and main activity and the way that this is going to work is I'm going to construct my home feed object from this body string somehow using a JSON builder so let's say Val G's son equals G's son which is somewhere over here you saw builder perhaps and parentheses parentheses C create I think I have to call it and now you can say G saw and dot from JSON type so you see you have a lot of these method calls you can use so we're going to use the string version and we will pass in the body string from above which is this guy over here and then the type is going to be the home feed so let's say comment and home feed so in order to get a type for a class using Colin you would say colon colon class Java so this is the type and you can kind of get rid of this over here because we don't really need it and so Val home feed equals all of this good stuff on the right side so let me remove that breakpoint put our breakpoint over here and I'll just hit command D to debug run inside of my Nexus 5 emulator and hopefully this stuff should all work and so my breakpoint should be hit down here and the moment that we get our body we construct our jisang builder class and then G son kind of performs all of the work to get our JSON string from body into this home of the client so down here is the debugger information for home feed so body is over here and home feet is a class that contains ArrayList of videos now so video is over here we have ID and then we have a name which is Instagram firebase and then we have one which is intermediate training core data and the Kindle basic training course so over here you see all of these videos and that's kind of what's being rendered out using the JSON data so that is pretty darn good okay so now that you understand how to get our home feed let me show you how to grab the rest of our properties instead of our JSON blob over here for example link image URL and channel we need to grab all this stuff so how am I going to do this well let me see if I can copy this and paste it into my code somewhere so I can reference it so let me paste it up here I suppose and that's a pretty good comment that I will just say comment like that and so video this is pretty much my video has ID name and you have to say Val to make your properties publicly accessible so Val link of strings eval image URL of string as well and make sure you are typing in the correct property names the spelling and the case is actually sensitive so make sure you do it correctly and over here you can say number of views you type in two like that and so yeah this other class inside of this video class so the way that you would capture the channel data which is let's see this over here and let's build that app that's the channel data you just have to create another model object call it Channel and since out of here you know you create the rest of the properties of name profile image URL so make sure to add the avowal profile image URL type string and you can also capture a number of subscribers if you really wanted to do so all right so now with that change and let me hit that debug button again to make sure my code fire is off and I want to hit the breakpoint one more time to confirm that my data is correctly placed inside of my videos array so open that guy up we have the ID in majority I'll link name and we also should have channels somewhere so I don't see a channel yet because I don't have it inside of this class so you should probably hit enter there hit vouch Channel devout Channel and channel and I think this is missing a vowel so let me add a vowel there and I can run my code one more time so I just a command or control D to Dib bug and the debugger is actually really useful inside of the Android studio editor so home beam let's just see one more time what's inside of the first slot so we have channel we have let's build on AB profile image URL so really good stuff there I can hit the continue and everything should be okay alright so the question now is how do i exactly use the home via to fill out my entire list which is this main adapter over here so we have video titles and we have these couple of items so what you really have to do is you have to modify main adapters so that you can hold a reference of your home feed so the way I'm going to do that is to modify main adapter to have a constructor that takes in some properties here so this will be home feed and we'll say home feel like that so it's very similar to what we just did with our previous model classes this is going to have our main adapter kind of contain a publicly accessible home feed parameter so down inside of here you probably can use Home Videos dot count instead so this is returning for currently so one two three four and so let's use home feed instead so instead of here we have access to home feed and we also have video and then finally you can either use size or account not exactly sure which one is better yet so let's just you just count for now and we can try to run our application but I know it actually doesn't work because main adapter over here at the constructor has now been modified so let me type in an e this actually requires you to pass in a home feed object now so this doesn't really help us do anything currently instead I'm going to comment that out and if you run your code now you don't really get anything so I'm just hitting ctrl R to run my app quickly and now we get nothing because I just commented that out and the last step that we need is to somehow say recycler review main which is what we're doing up here recycler view main and we can say dot adapter equals main adapter and inside of here we have home feed so let's just pass it in there and try to run our code one more time so I'm not exactly sure if this works yet I guess we'll see and you see our application has stopped right so let's go inside of logcat to see exactly what does happening so it says somewhere down here that let me show you what's going on only the original thread that can or that created a view hierarchy can touch its views so if you're kind of familiar with iOS and Swift you have to modify your UI on the main thread and all of this stuff is actually executing on a background thread so in queue makes sure that everything is kind of going on I'm in the background and down here all you have to do is say a run on UI thread so this magical magical method select the bottom one with you three dots just hit enter you just want to cut that and paste that in there should be good to go so let me run my application one more time yeah and our code will now contain the three items instead of the previous four so the reason why that is is because our JSON blob only has three videos so one two and three and it still says the wrong titles of first second and third so go back to you main adapter and now you can modify your on buying a view holder and here is kind of where you might have been confused last time and let's see what do I want to do well we're setting the video title equal to this video titles array and we're just getting the position so now all you have to do is comment that out and say perhaps Val video equals I don't know home feed that seems to work videos and just use get and position that'll gives your videos so you can just say video now here which is your video motto object and you can also see name like that and now you can run your code maybe I'll just hit instant run to make it a little bit faster and so once you do that you have your titles showing inside of your views very very easily so this is view it's actually coming from your custom view holder and this view is this view over here and custom view holder it's kind of manages the view for each one of your rows you can think of it that way it's a little bit complicated but you know that's the simple explanation for it all right so that's gonna wrap it up for today's lesson on how we can very easily consume JSON data from an arrest API service and as you can kind of tell through today's lesson we use the help of a couple of really really good third-party libraries such as okay HTTP and also ji-sun to kind of make our code very very simple and clean right we only need just a couple of lines to fetch our JSON data and also convert our JSON string into very easily usable model objects don't forget if you want to download the source code for today's video and the project you can find the link down below in the description that's gonna be it for me today hopefully I'll see you in the next bye bye and don't forget to subscribe peace
Info
Channel: Lets Build That App
Views: 74,345
Rating: 4.9080458 out of 5
Keywords: development, tutorial, learn, xcode, programming, code, android
Id: 53BsyxwSBJk
Channel Id: undefined
Length: 26min 14sec (1574 seconds)
Published: Wed Dec 20 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.