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

okhttp responsebody can not be converted to a string. Please help...

--truncated-Rain","icon":"rain","precipIntensity":0.0297,"precipProbability":0.67,"precipType":"rain","temperature":78.89,"apparentTemperature":78.89,"dewPoint":68.96,"humidity":0.72,"windSpeed":9.68,"windBearing":6,"cloudCover":0.99,"pressure":1010.87,"ozone":242.75},{"time":1421060400,"summary":"Light Rain","icon":"rain","precipIntensity":0.0249,"pr 01-11 18:34:32.296 2007-2020/com.bravemindstz.stormy V/MainActivity﹕ [ 01-11 18:34:32.316 2007: 2020 V/MainActivity ] Exception caught : org.json.JSONException: End of input at character 0 of at org.json.JSONTokener.syntaxError(JSONTokener.java:450) at org.json.JSONTokener.nextValue(JSONTokener.java:97) at org.json.JSONObject.<init>(JSONObject.java:155) at org.json.JSONObject.<init>(JSONObject.java:172) at com.bravemindstz.stormy.MainActivity.getCurrentDetails(MainActivity.java:85) at com.bravemindstz.stormy.MainActivity.access$100(MainActivity.java:23) at com.bravemindstz.stormy.MainActivity$1.onResponse(MainActivity.java:62) at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162) at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841)

Ken Alger
Ken Alger
Treehouse Teacher

Ally;

Can you post, or link to, your MainActivity.java file? It looks like there might be something going on with your getCurrentDetails() method.

Ken

6 Answers

Hi Ken

Here is the MainActivity.java

package com.course.practising.stormy;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


public class MainActivity extends Activity {

    public static final String TAG = MainActivity.class.getSimpleName();

    private CurrentWeather mCurrentWeather;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stormy);

        //double latitude = 37.8267;
        //double longitude =  -122.423;
        String apiKEY = "385402ba95335407fae83737763a0984";
        //String forecastUrl = "https://api.forecast.io/forecast/" + apiKEY + "/" + latitude + "," + longitude;

        String forecastUrl = "https://api.forecast.io/forecast/385402ba95335407fae83737763a0984/-6.8,39.2833";

        if(isNetworkAvailable())
        {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(forecastUrl)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        Log.v(TAG, "Check Log " + response.body().string());
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData.toString());
                        if (response.isSuccessful()) {
                                mCurrentWeather = getCurrentDetails(jsonData);
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.v(TAG, "Exception caught : ", e);
                    }catch (JSONException e)
                    {
                        Log.v(TAG, "Exception caught : ", e);
                    }
                }
            });

            Log.d(TAG, "Main thread is running");
        }
        else {
            Toast.makeText(this,getString(R.string.network_unavailable_message),Toast.LENGTH_SHORT).show();
        }

    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {

        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        Log.v(TAG, "From JSON : " + timezone);
        return new CurrentWeather();
    }

    private boolean isNetworkAvailable() {

        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected())
        {
            isAvailable = true;

        }
        return isAvailable;
    }

    private void alertUserAboutError() {

        AlertDialogFragment alert = new AlertDialogFragment();
        alert.show(getFragmentManager(), "error_dialog");
    }
}

Hello

Does anyone have an answer?

Ken Alger
Ken Alger
Treehouse Teacher

Ally;

I'll take another look at this tonight. Sorry I dropped the thread on this.

Ken

Ken Alger
Ken Alger
Treehouse Teacher

Ally;

I wound up getting the same error with your code. Generally the "End of input at Character 0" error means that it cannot find some/all of the JSON data. I'll keep working on it but perhaps you already have it solved?

Post back with updates.

Ken

Ken,

I have not solved it yet.

The weird part is that am getting a clean JSON data through the browser. Am getting this error through my code and its the same code from Ben. I have tried to check the forum, google! nothing.

Thanks.

Yiheng Chu
Yiheng Chu
8,465 Points

I meet the same problem. Have you solve the problem?

I'm also having the same issue.

Simon Coates
Simon Coates
28,694 Points

I had this exception. I verified that the json i was getting back from the response was valid (not truncated), but the trouble for me was that the value was somehow replaced by "" prior to being fed into the parse method. So my suggestion is a) confirm you're getting back good JSON and b) confirm that JSONObject forecast = new JSONObject(jsonData); works by feeding it some verified data (copy JSON into java as a string, replacing quotation marks with escape characters). If you isolate where the break occurs you should be able to fix the problem. Worst case, you can try replacing the libraries that do the request or the parse to isolate the error (this assumes one of the libraries in use is flawed).

(this advice is mostly in the event someone new stumbles over this error. In which case, good luck, and apologies if my explanation of debugging technique is simplistic)

Simon Coates
Simon Coates
28,694 Points

FYI, if having some difficulty seeing the full json (as i did), you can reduce the amount of json you get back. eg.

String url = "https://api.darksky.net/forecast/" + API + "/" + latitude
                    + "," + longitude+"?exclude=minutely,hourly,daily,flags";

nb: the url seems to have changed since the video was recorded.

I have encountered the same issue while trying to write the Stormy application and also while trying to use this knowledge on another app. Has anynone solved this issue yet?