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

Manas Vijaywargiya
Manas Vijaywargiya
12,598 Points

data is not displayed. @benjakuben

After making the whole weather data app, the app in not able to retrieve data from the site - dark sky API

Ben Jakuben

Manas Vijaywargiya
Manas Vijaywargiya
12,598 Points

MainActivity.java:- Ben Jakuben

package com.example.manas21094.stormy;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    private CurrentWeather mCurrentWeather;

    @InjectView(R.id.timeLabel)TextView mTimeLabel; //Butterknife annotation
    @InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
    @InjectView(R.id.humidityValue) TextView mHumidityValue;
    @InjectView(R.id.precipValue) TextView mPrecipValue;
    @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
    @InjectView(R.id.iconImageView) ImageView mIconImageView;
    @InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
    @InjectView(R.id.progressBar) ProgressBar mProgressBar;

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

        mProgressBar.setVisibility(View.INVISIBLE);

        final double latitude = 37.8267;
        final double longitude = -122.4233;

        mRefreshImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getForecast(latitude, longitude);
            }
        });

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

    }

    private void getForecast(double latitude, double longitude) {
        String apiKey = "{{REMOVED}}";

        String forecastUrl = "https://api.darksky.net/forecast/" + apiKey + "/" + latitude + "," + longitude;


        if(isNetworkAvailable()) {
            toggleRefresh();

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

            Call call = client.newCall(request);  //Anonymous Class
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    alertUserAboutError();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught : ", e);
                    } catch (JSONException e){
                        Log.e(TAG, "Exception caught : ", e);
                    }
                }
            });
        }else{
            Toast.makeText(this, getString(R.string.network_unavailable_message),
                    Toast.LENGTH_LONG).show();
        }
    }

    private void toggleRefresh() {
        if (mProgressBar.getVisibility() == View.INVISIBLE) {
            mProgressBar.setVisibility(View.VISIBLE);
            mRefreshImageView.setVisibility(View.INVISIBLE);
        } else {
            mProgressBar.setVisibility(View.INVISIBLE);
            mRefreshImageView.setVisibility(View.VISIBLE);
        }
    }

    private void updateDisplay() {
        mTemperatureLabel.setText(mCurrentWeather.getTemperature() + ""); //""is used to remove error & make it it string
        mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + "it will be");
        mHumidityValue.setText(mCurrentWeather.getHumidity() + "");  //""is used to remove error & make it it string
        mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
        mSummaryLabel.setText(mCurrentWeather.getSummary());

        Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
        mIconImageView.setImageDrawable(drawable);


    }

    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("precipProbablity"));
                currentWeather.setSummary(currently.getString("summary"));
                currentWeather.setTemperature((int) currently.getDouble("temperature"));
                currentWeather.setTimeZone(timezone);

        Log.d(TAG,currentWeather.getFormattedTime());

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

2 Answers

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

I'll walk you through my troubleshooting steps, but take a minute and see if you can trace it yourself by looking at the error message from logcat, because it'll help you solve these kinds of issues when they inevitably pop up in the future. This is a common error, unfortunately! :)

(By the way, I removed your API code from the paste above.)


I plugged your code into my app and found the following error in logcat:

02-13 15:54:54.127 6177-6723/teamtreehouse.com.stormy E/MainActivity: Exception caught : 
    org.json.JSONException: No value for precipProbablity
    at org.json.JSONObject.get(JSONObject.java:389)
    at org.json.JSONObject.getDouble(JSONObject.java:444)
    at teamtreehouse.com.stormy.ui.MainActivity$override.getCurrentDetails(MainActivity.java:163)
    at teamtreehouse.com.stormy.ui.MainActivity$override.static$access$500(MainActivity.java:31)
    at teamtreehouse.com.stormy.ui.MainActivity$override.access$dispatch(MainActivity.java)
    at teamtreehouse.com.stormy.ui.MainActivity.access$500(MainActivity.java:0)
    at teamtreehouse.com.stormy.ui.MainActivity$2.onResponse(MainActivity.java:107)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)

If you click on the link in logcat to the error in MainActivity.java (line 163 in my code), it takes you to this line of code:

currentWeather.setPrecipChance(currently.getDouble("precipProbablity"));


I manually confirmed that the JSON was coming back as expected from the Dark Sky service, but I didn't really have to.


Knowing that precipProbability was in the JSON data as expected, I looked more closely at this line of code. I found an easy-to-miss typo in the key you're passing in to the getDouble() method: you're missing a lowercase "i" in "Probability".