Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Weather App Working with JSON Setting CurrentWeather from JSON

what exactly is the job of storing : response.body().string(); in jsonData?

question in title. why we need to store it like that and then use it as a parameter for the getCurrentDetails method?

  String jsonData = response.body().string();

Lauren Moineau

2 Answers

Hi noob developer. We need to store it in a variable as the response body can only be consumed once in OkHttp. When we call string() on response.body(), it reads the stream, processes it (converts it into a string) and closes it. If we were to call parseForecastData(response.body().string()) later, response.body().string() would be empty this time as the stream has already been consumed. So storing it in a variable allows us to access it several times in the code.

Hope that helps :)

We can use response.body().string() without storing it in a variable and every thing would work the same...

But it's good coding practice to define and assign a jsonData variable once and then use it, instead of calling response.body().string() at multiple times. This is called Refactoring, which in this case, increases our code readability