Kotlin Youtube - How to Quickly Fetch Parse JSON with OkHttp and Gson (Ep 2)
Вставка
- Опубліковано 19 гру 2017
- Episode 1: • Kotlin UA-cam: Intro ...
Today, we learn how to fetch JSON data and integrate it using Model objects in our application. What's going to make our lives a lot easier is to use the help of OkHttp and Gson to fetch and parse our objects. Once we construct a HomeFeed model containing a list of videos, we will modify MainAdapter to dynamically render our list using this REST api endpoint. Enjoy.
HomeFeed Json Endpoint: api.letsbuildthatapp.com/yout...
OkHttp: square.github.io/okhttp/
Gson: guides.codepath.com/android/l...
Intermediate Training Core Data
www.letsbuildthatapp.com/cour...
Instagram Firebase Course
www.letsbuildthatapp.com/cour...
Facebook Group
/ 1240636442694543
iOS Basic Training Course
www.letsbuildthatapp.com/basi...
Completed Source Code
www.letsbuildthatapp.com/cour...
Follow me on Twitter: / buildthatapp
In case anyone is having the problem I had - in the build.gradle file, if you write what Brian wrote ("compile..."), it'll show up with a line crossed through it. If you hover your mouse over that text, it'll tell you that "compile is deprecated, replace with implementation" - so you basically just replace the keyword.
I would've figured this out sooner if I'd known to hover over that text, haha!
Awesome videos, Mr. Voon! 10/10! Thank you!
Your systematic approach to programming and explanations make your vidz worth watching. Thanks Brian!
Brian has a casual, easy demeanor that makes him a good instructor. I recommend this video.
3 years later, still a life saver. Clear and concise, also great demo of 'Debug' too 👍
After watching your tutorials, it feels so comfortable to start with Android development using Kotlin. Thanks Brian!
How can someone dislike this master piece? Thanks bro, those libs to work with Json and HttpRequest are really, really great! Youre a beast!
This video helpt me A LOT! I have a deadline and don't have the luxury to dive into the documentation. Thanks for explaining this so easily!
You're so chill. I feel like I could smoke a blunt with you and talk about various code syntaxes.
Amazing tutorial. Watched countless other tutorials and none of them told me to add the internet permission in the manifest, hence my errors. You made this very clear and simple to understand. Thank you!
Thank you. I had like 3 hours trying to parse a JSON from an API and thanks to you I was able to do it. Not only that, but I think I actually understand the process and will be able to repeat it in the near future. Gracias.
Hey, I'm really lucky I found you. Your videos are too good, really. I really needed something practical yet super clear in order to build my application for a uni course in about 15 days without knowing kotlin at all (I refused to use java, I really dislike it).
Took me so long to find a decent tutorial on this! Thank you! Great video and explanations!
Thank you so much for all your hard work :) When ever I want to learn something new.. your videos are always what I need . Please keep it up
Been following your through iOS and now Kotlin. You have a gift for teaching.
Glad to have you follow the channel, isn't great that we can program in so many languages?
I Love these tutorials, Easy to understand and very helpful videos.
Hay Brain, thank you for a magical outstanding experience to get me back on a fast track for mobile development. I am very grateful to come across someone who loves to grow through sharing knowledge like you. I am loving this Kotlin track even through my heart is set on iOS :D
I want to take the opportunity to wish you and all your loved ones a brilliant holiday season and more success and prosperity in the new year.
i wish you could get a million views. Thank u so much, this is very easy to follow
I applied for a job 1 week ago and this was my sort of task to get an interview. Basically if i am going to be accepted on this internship it's going to be just because of you
Thank you
You have taught me Obj C first. Then Swift. And now Kotlin. I think I owe you a drink :D
adamın heykelini yapsak taşaklara beton yetmez
Very nicely presented. Just right for a tutorial.
Hey Dude you are doing great job. Thank-you for the videos.
Great videos! Thank you so much. :)
Loving it!
Thanks for the tutorial !! :D
same as always, very helpful, thank you
Thank you !!! , you just saved me in my 400 level class
I LOVE these Android tutorials
Everything's nice and easy eh?
Lets Build That App I really like that you compared some of the elements to the corespondent elements in swift. Makes it easier, please keep doing that :-)
But yeah, some concepts I can’t understand 100%
After you get over the initial "new syntax" scare, it becomes the same thing but in a new language. Good ol fetch json, load images. Rinse and repeat.
I love you dude, you save my life
SOOOO grateful!! Thanks!!!
thank you very much.This video is very help full for me
owesome video is symple and just go in what we need thankssss a lot
ps:from a brasilian fan
UR VIDEOS ARE SUPERB!
For everyone having trouble with Gson not parsing array, if your Json starts with a "[", make sure to use YourClass. Also, if it starts as an array, the example that he have using the HomeFeed class won't work, you would need to use the Video class directly. Watch out for the format of your Json.
could you please send an example of the code? and how can I change the format of my Json?
Thank u for this awesome video
love your work your video , thanks alot
Thanks your video are awesome.
Hi, Brian! Awesome videos, best way to get job in software dev field is DO DEV!:) Could you make a video explaining how to use RPC. Can't find answers for json-rpc2.0 using Kotlin. THX!!!
Hi brian, this a great video! Im an iOS developer, and im writing my first kolin lines. I like to write code like i would do with swift, so i created a network manager class to fetch the json. All is fine, however, i dont know how to return this data to my main activity. In swift i would do this with a completion block on the the fetchJson(), but i dont know if there is something similar in kotlin. Also, intercepting the adapter from my network manager class, is something i want to avoid because its not the purpose of this class to update the UI with the new data. How do i return data properly?
hi man, i have a question, i am doing this with maps, but i dont know how call the mainthread on response, to reload the map when the points are loaded, something like layoutViews or something
Hello, How do you tackle the case whereby the user has no active internet connection?
thanks profesor brian
These are great videos, thanks Brian. There's a minor syntax change with the latest Android Studio/Kotlin libraries:
At the 10:42 point in the video, the syntax is:
override fun onResponse(call: Call, response: Response)
It seems to be no practical difference, but Kotlin insists that the declaration of an overridden function is EXACTLY the same as the abstract declaration.. ..
Aah, there's another small syntax change on the next line, it should be:
val body = response.body?.string()
Cheers.
thank you very much, I'm studying this. in this section, I found an error in the code that I tried from the tutorial. I read read a few comments. I found the answer here ... I am very happy ...
Dude u r a savior!
let the beginners know that the list is meant for the jsonarray and the world isn't over... it took me hours to figure that out. that aside your tuts are very helpful
Me too. Took a little while to work out what was going on there.
sir.. are the lessons/tuts that the link you've provided below is for free.? or if isn't how can i enrolled in your class on android dev. especially on kotlin courses..
Thank you so much . bro 😊😊
The videos are really great. I just wanted to point one thing out - I guess we can also make HTTP calls in a more simple way: using threading and the URL library, it boils down to one line: Thread({ val response = URL("").readText() }).start()! You still need to use Gson to convert it into a model, but I found this to be the easier way...
Hmm....really? I gotta brush up on the Threading library.
Yeah! I discovered it a few days ago myself. And it's much simpler with Kotlin than it was in Java. The one downside though is that you do have to use try-catch statements as the inbuilt URL library throws a fatal exception when it can't read a url...
Could you please post the code with your solution?
Hey, like I said. The code is just this much:
Thread({
val json = URL("").readText();
val object = Gson().fromJson(json);
runOnUiThread({
// do something with the object...
});
}).start();
Love You Bro
man, nice job
Is there gonna be tutorial for populating recyclerview from, say, an xml file within the product package instead of loading it from the internet?
Thank you bro
Hey, great tutorial... But having lots of trouble with API links that have parameters
Only the original thread that created a view hierarchy can touch its views.
how to solve this in fragment? you cannot use runOnUiThread on fragment
Should the homeFeed & Video classes be 'data class' rather than just 'class'?
yes that would been have a better approach....!!!!
Hi, I need your help. I have a live portal with database how can I convert into an Android app
Thanks! Very helpful!. Just wondering if you have any tips for refreshing yourself with Xcode? Like if you've taken a break from it for awhile.
Hi! Thank you for the video. Do you use x86 or arm emulator?
make some tutorial on augmented reality in Android.Ur tutorials are awesome
First...!!!!
Good video, keep it up ... !!!
There's an error inside of runonuithread because I'm getting that homefeed is null inside the runonuithread
very nice
Retrofit vs okhttp? Which one shall we prefer
nice tutotials
In 2021, is okhttp and gson still the recommended thing to use to build something like this?
Google their github activity
Thanks )
thnks
Can you show dynamic horizontal recyclerview to dynamic vertical recyclerview with jain parse...pls
Can Anyone help me cause I am having errors in my thread.java file yet i didnt even edit it@android 3.3
Just a quick note to watch out for. This took me about an hour to realize.
Don't use body = response?.body()?.toString()
use:
response?.body()?.string()
ResponseBody has its own to string function - string()
Do you fixed the problem?
body() is deprecated, use body like variable instead it
very good !! can you please tell me how to parse json array instead of json object ???
Hi Brian, The video is really helpful. I just wanted to ask a question how can I use OkHttp with request method POST in Kotlin? Thanks
I'd go ahead and use the method shown here for POST requests:
stackoverflow.com/questions/23456488/how-to-use-okhttp-to-make-a-post-request
Great. Thank you so much
I'm getting an error when using fetchJson, "E/zygote: isWhitelistProcess - Process is Whitelisted. Does anyone know how to get around this? I'm using my Samsung S7 as my emulator, its never given me this error before. Any help appreciated!!!
First of all, i got through all EPISODE 1 without any problem. Now On EP 2 I got suck with System.Out to display the vakye as the OnResponse(call: Call?, response: Response? ) is not working especaily the val body. response?.body()?.string() wich is string is toString() on mine .. it showing NULL value when it comes to the body... what am i doing wrong? please help!
hey. i have a question. if i go another activity and still need the same data what should i do. is there a way to make "val homeFeed" accessible frown any Activity ?
We go over this in the next lessons right? I might be going crazy after reading comments
Hi, nice tutorial, how do i change the url ?
I just wanna say "i will click a lots of ads on your tutorials" !!!!!!
if you install android studio fresh and when you run the okhttp it is not working make sure your emulator can reach the internet.
to test hit home on the emulator and click chrome go to yahoo.com. if it doesnt work go to android studio preferences ( on a mac ) and type in proxy make sure the android studio is using the current wifi connection
then go to the emulator and make sure the proxy tab says to use android studio
test yahoo.com again and your all set.
hope that helps anyone new and having issues
Hey I tried changing my url to my localhost one and it suddenly don't work , can anyone help me?
What is different of Gson and Volley?
iam hoping you will make Android development courses as you did for ios development
Hello Brian,
That's an excellent tutorial. I am implementing it, I did have some differences in the structure (my JSON was an array instead of an object, but I found out how to fix that. I am having another problem though, I am using this code inside a fragment and when I try to use the runOnUiThread { } block, it's marked as red and it's not working, any idea how I could fix that?
Excuse me, could you tell my how you fix your first problem? I’m new to Kotlin and also my JSON is an array...
@@andreaculot99 hello, sorry for the late answer, I ended up switching libraries to RetroFit2 and it worked like a charm :) almost didn't have to change code.
Quick side question, how do we set custom colors when using API 15? Everything I'm trying seems to require API 26. Thanks!
What have you tried?
Color.argb requires API level 26
However, I found Color.parseColor("#HexValue") to work, is this the only option?
Yep, i've used parseColor in the past. Is there a reason you're not using targetSdkVersion 26? My configurations use:
minSdkVersion 15
targetSdkVersion 26
My debugger is telling me that I am getting NULL values in my class when converting Json to Gson in: val homeFeed = gson.fromJson(body, HomeFeed::class.java) I can't seem to figure out why or how I can mitigate this. (I am using my own variable names and a different API)
please make some video to do same with Retrofit..
Thank you..
If you get an OkHttpCliient error "failed to execute request" here's what to try:
(*) Double-check the url is correct - it's "api." not "www."
(*) Add the following line to the onFailure function to give more details in the logcat about the error:
Log.i("LBTA", e.message)
(*) Test your OkHttpClient code by using a different JSON feed: This is a public testing feed that I used:
url = "jsonplaceholder.typicode.com/posts"
If you see some json in your logcat, then you know your code is okay, and that the problem lies with the server.
Hope this helps.
If the error message in the logcat is something like socket failed: eperm (operation not permitted), you can also try uninstalling the app from the emulator and debugging it once again.
My code moves to the onFailure function call and gives me an error "System.out: socket failed: EPERM (Operation not permitted)"
mine too, idk why
@@marshal7969 Delete the app from the emulator and run again
@@BuildezCraft that worked for me, thanks!
Is it a better practice to keep models in separate files?
Probably, why do you ask?
Hello ! I am having a big problem. When I compile, the function prints out what is written when onFailure but not when onResponse. how to fix it? I tried other .json files but still the same
I found the problem :D it is because your phone is sleeping.. :D unlock it and then compile :D
How you have created this api I mean if using sql then on what server or is it heroku?? Your information mean a lot. Thanks :)
i have the same problem
I know this is an older comment - and wanted to write something just in case someone read it in the future and had the same question. Depending on your language determines how you generate your data - the API is just JSON nothing more, nothing less. Converting your objects to a json object should be simple, search "your language data to json" should give you some insight -- now I will say -- make sure your data is not in a parent array - I had this break on me -- meaning your data starts like this [....] vs {} - best of luck.
Why don't you use retrofit to parse the data
The videos are great, but I feel like your microphone might be slightly not loud enough? I'm comparison to other videos, this one is probably at 70-90% volume whereas I listen to others at like 40-50%.
Anyways, the content and the videos are amazing! :)
Brian, I did a navigationButton with three items.
I visualize (as you do to check) that each fragment is shown when selecting each item.
My query is, to apply your course to a fragment, is it the same? What if it was an activity? or with a fragment does the programming change?
Each fragment should be its own entity. Once you load one, loading a second one is pretty easy.
I do not realize how to do it ...? Will you have a tutorial or do you know any guides? THANK YOU!
Google pretty much shows you how to load a fragment right?
yes, until the fragment shows up, and upload a text manually, too, I have the problem in showing the data from the json ....
You should probably load the json then, no?
Thanks for the really great videos, Brian. I'm getting this error from the OkHttpClient: "Trust anchor for certificate path not found". Mr Google indicates that the SSL certificate on the server has expired or is mis-configured. These videos are well over a year old now and you don't have any responsibility to maintain them, but the context is still relevant and there are thousands of beginner developers (like me) that would get a lot of benefit out of them. So I hope this is something that is easily fixable.
Cheers.
Brian, apologies; I've found a solution. I was implementing a logging interceptor (an useful exercise in itself) and accidentally tested the project against a different virtual device in the emulator - and got a different INET exception (what?!). A bit of trial and error I found a virtual device that would make the project accept the api feed - Nexus 9 Android 7.0 (API 24). Weird. Having seen some advice that a good way to eliminate strange errors is to close the emulator and reopen it, I feel that I have bumped into one of those dark and mysterious areas of Android programming - and feeling a little bruised and humbled as a result, Apologies again.
@@philwatkinson5417 you've saved me hours of trial an error, thanks
I love you
Ok besides that OkHttp now allowing .execute().use which works - I could not get your method to work.
sorry for asking, why my api always Failed to execute request, i'll try to use your api anda another api. but it still not working properly
Need help too
I get the answer in the console but the homefeed class dosent show
Im getting this error when using a different url to parse an array. "Expected BEGIN_OBJECT but was BEGIN_ARRAY" Is there a simple fix? Ive altered all my classes to to adhere to the new url. Changing the home feed class to "Array" instead of "List" gives the same error. Im coming from iOS so I figure there has to a simple solution.
Episode 5 of this series explains how you would parse an Array of objects instead of an Object directly. Namely, you need to use Array::class.java.
You're really making the sub worth it. 👍🏽
Hi Sir.. do you have any video for filtering this recyclerview? 10q
I mean how to search data or filtering the search data
when i call fetchJson. it always return onFailure. is anyone know what happen?
i have the same problem, do you know what happend?
i found the problem :D it is because the phone is sleeping . unlock it and then compile ;D
@@cerdek9190 Have you found a solution?
Please do reply... is there a proplem in storing a big json from a real estate api..like hundreds of proporties..in a string for parsing. Do u lose info? Please do reply!!
Yes, its called a database. You can use a free setup called Firebase. I have lessons on this in the description below with the Instagram Firebase course.
Bryan thanks for the reply, but what i meant was thati'm fetching 100s of pages worth of json from a third party real estate api, so im lot allowed to store the data.But is there a probem if i fetch it and store in one string variable for parsing??is it the righy way?
response?.body()?.string is not working for me.....idk y...🥺🥺