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 (2015) Working with JSON Setting CurrentWeather from JSON

Benjamin McKenzie
Benjamin McKenzie
7,455 Points

Okhttp response.body().string() empty only when logged first?

@Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response.isSuccessful()) {
                        //Log.v("Okhttp request", response.body().string());
                        mJSONData = response.body().string();
                        populateWeatherData(getJSONData());
                        setTimeString(formatTime());
                        Log.i("icon", getIcon());
                        Log.i("time", getTimeString());
                    }
                }   catch (IOException e) {
                    e.printStackTrace();
                }   catch (JSONException e) {
                    e.printStackTrace();
                }
            }

The above code works, but if I uncomment the Log.v line, mJSONData is initialized to an empty string, not null just empty. The strange thing is that when I log the json data, it is correct. It's as if calling response.body().string() in the log line makes the string empty after it is called. Does anyone know why this is?

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

Apparently it's designed that wayFrom https://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/Response.html : "Instances of this class are not immutable: the response body is a one-shot value that may be consumed only once."