0

Here is my MainActivity class for a project where I am trying to call a JSON formatted link that has forecast info:

public class MainActivity extends ActionBarActivity {

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

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

        String apiKey = "bf092d4688e81db384b589d7a225e061";
        double apiLat = 37.8267;
        double apiLong = -122.423;
        String forecastURL = "https://api.forecast.io/forecast/" + apiKey + "/" + apiLat + "," + apiLong;
        if (isNetworkOnline()) {
            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 {
                        String JsonData = response.body().toString();
                        Log.v(TAG, response.body().string());
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(JsonData);
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException | JSONException e) {
                        Log.e(TAG, "Caught exception: ", e);
                    }
                }
            });
        } else {
            Toast.makeText(this, getString(R.string.network_not_available), Toast.LENGTH_LONG).show();
        }
        Log.d(TAG, "Main UI code is running.");
    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
        // getting the first JSON object in the json formatted link.
        JSONObject forecast = new JSONObject(jsonData);
        String timeZone = forecast.getString("timezone");

        // getting the second JSON object in the json format by looking for the
        // keyword "currently"
        JSONObject currently = forecast.getJSONObject("currently");
        CurrentWeather currentWeather = new CurrentWeather();
        currentWeather.setHumidity(currently.getDouble("humidity"));
        currentWeather.setIcon(currently.getString("icon"));
        currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
        currentWeather.setSummary(currently.getString("summary"));
        currentWeather.setTemperature(currently.getDouble("temperature"));
        currentWeather.setTime(currently.getLong("time"));
        currentWeather.setTimeZone(timeZone);
        // Displaying the formatted time from seconds to the format we
        // specified.
        Toast.makeText(MainActivity.this, currentWeather.getFormattedTime(), Toast.LENGTH_LONG).show();
        return currentWeather;
    }

    private boolean isNetworkOnline() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

However, this error keeps popping up and i'm unsure what this error is saying and why it is occurring.

07-21 01:37:10.644  20859-20908/com.example.android.stormy E/MainActivity﹕ Caught exception:
org.json.JSONException: Value com.squareup.okhttp.internal.http.RealResponseBody@423e87e0 of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:111)
        at org.json.JSONObject.<init>(JSONObject.java:158)
        at org.json.JSONObject.<init>(JSONObject.java:171)
        at com.example.android.stormy.MainActivity.getCurrentDetails(MainActivity.java:73)
        at com.example.android.stormy.MainActivity.access$100(MainActivity.java:22)
        at com.example.android.stormy.MainActivity$1.onResponse(MainActivity.java:54)
        at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:170)
        at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
Ian2thedv
  • 2,691
  • 2
  • 26
  • 47
Voctave
  • 141
  • 7

1 Answers1

0
java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:111)

This probably appears because the web service that you are using is not returning the jsonObject

it may happen when the key that you are sending to your web service is incorrect or it may happens if the key value is a duplicate for some primary key in the database or it may be your web service that causes that.

Possible Solutions:

make sure that the keys are correct and match your web service keys, debug and find out what is the returned json string to know if its duplicate and change the value that you are trying to send, make sure that your web service returns a valid value after changing it to GET and send params through the URL.

Or it may be caused by un-wanted characters was added when you compose the String if so; chick out this.

Community
  • 1
  • 1
Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56
  • I tried debugging but despite being "Connected to the target VM, address: 'localhost:8615', transport: 'socket' " - It doesn't show any frames in which I can veiw the variables and their values. – Voctave Jul 21 '15 at 06:38
  • put a break point on JSONObject forecast = new JSONObject(jsonData); and let us know what is the value of jsonData – Ahmad Sanie Jul 21 '15 at 07:24