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

status 401
status 401
13,811 Points

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