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 Introducing JSONObject

Why does my code not call the api server, and why do I have OpenGLRenderer errors in my logcat?

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 = "5fffb4bcaef4b85f70632d7dc2d2b26c";
    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() { //asynchronous call
            @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 | JSONException e) {
                    Log.e(TAG, "Exception caught: ", e);
                }
            }
        });
    }
    else{
        Toast.makeText(this, getString(R.string.network_unavailable_message),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 = forecast.getJSONObject("currently");

    CurrentWeather currentWeather = new CurrentWeather();
    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setIcon(currently.getString("icon"));
    currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
    currentWeather.setSummary(currently.getString("summary"));
    currentWeather.setTemperature(currently.getDouble("temperature"));

    return 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");
}

build.gradle (Module:app)

apply plugin: 'com.android.application'

android { compileSdkVersion 21 buildToolsVersion "21.1.1" defaultConfig { applicationId "teamtreehouse.com.stormy" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" } 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:21.0.0' compile 'com.squareup.okhttp:mockwebserver:2.4.0' compile 'com.squareup.okio:okio:1.4.0' compile 'com.squareup.picasso:picasso:2.5.2' }

Also when running debugger I have no options to step forward or back and no variables are available "connected to the target VM, address: 'localhost:8608', transport: 'socket'

I checked my api key and I only have 1 call when I should have 20-30. I do not know how the 1 call occurred.

1 Answer

Hello,

It looks like you only have one call to the API in your code. You should only need 1 call since it gets all of the data that you will need and we just parse through that data to obtain all of the display values. Are you getting the long bulk data(likely to be truncated) in your logcat display? If so, everything should be working and you should have all of the data you need to parse through. Please let us know if you still need more help and we'll provide more assistance.

Thank you! You ruled out all the things I was worried about letting me to check on other factors. Turned out that I just needed to enable Wi-Fi on the virtual phone through genymotion. I did not think of this at first as I had a command to check network connectivity but of course the 3G service is not actually connected to anything!

Thanks again

Glad that I was able to help in some manner at the least. Interesting that it turned out that way with Genymotion. Have fun with Android development.