Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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