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

Cannot resolve symbol getJSONObject

For the Stormy app, I'm trying to get weather data from a JSONObject but Android studio is not recognizing the getJSONObject symbol, even though it comes as a suggestion.

I've already tried: 1) Adding compile 'org.json:json:20141113; to the gradle 2) Adding json-simple and gson- 2.2.4 jar files

I even see the org.json.JSONObject library imported as well.

The compile error says 'package forecast does not exist' , forecast is the JSONObject variable I created.

Not sure what to do here. Please help.

Hmm. Can you include your build.gradle and MainActivity.java code...so we can see what may be wrong?

package com.townsee.stormy;

import android.app.DownloadManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; 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 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 = "05cab61d21636f623158e406038a7540";
    double latitude = 37.8267;
    double longitude = -122.423;
    String forecastUrl= "https://api.forecast.io/forecast/" + apiKey +
            "/" + latitude + "," + longitude;

    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 {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mCurrentWeather = getCurrentDetails(jsonData);
                    } else {
                        alertUserAboutError();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "Exception Caught: ", e);
                }

                  catch (JSONException e) {
                      Log.e(TAG, "Exception Caught: ", e);
                  }

            }
        });
    }

    else {
        Toast.makeText(this, getString(R.string.network_unavailable_errorMessage),
                Toast.LENGTH_LONG).show();
    }

    Log.d(TAG, "Main UI code is running!");

}

private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    Log.i(TAG, "From JSON: " + timezone);

    JSONObject currently = new forecast.getJSONObject("currently");

    CurrentWeather currentWeather = new CurrentWeather();

    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 dialog = new AlertDialogFragment();
    dialog.show(getFragmentManager(),"error_dialog");
}

}

apply plugin: 'com.android.application'

android { compileSdkVersion 23 buildToolsVersion "23.0.1"

defaultConfig {
    applicationId "com.townsee.stormy"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}


packagingOptions {
    exclude 'LICENSE.txt'
}


buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.0' compile 'com.squareup.okhttp:mockwebserver:2.5.0' }

2 Answers

org.json is included as part of the Android OS API. It doesn't need to be included an external library or jar at all. Trying to do so is probably causing a conflict, thus the error. Remove the jars and the compile line from build.gradle then Sync Project and rebuild.

I started off with the same, but again removed the jars and compile line from build gradle and rebuilt the project. I'm still getting that error.

Added my build gradle and main activity code for details.

Stack Overflow came to the rescue. Posting it here for anyone who made the same mistake:

"Your problem is in this particular line:

JSONObject currently = new forecast.getJSONObject("currently");

You don't need to use new to get the JSONObject, the IDE thinks forecast is a type or a package and it can't find it in your project so it's throwing an error, you should change the previous line to this:

JSONObject currently = forecast.getJSONObject("currently");

Hope it helps you, happy coding."