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

l can't invoke onResponse() method. Only onFailure method invoked

public class MainActivity extends ActionBarActivity {

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

    @InjectView(R.id.timeLabel) TextView mTimeLabel;
    @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;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        String apiKey = "d6f19c3a3f27d3b7a16266bf79b6fc25";
        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) {
                    Log.d(TAG,"onFailure");
                    mTemperatureLabel.setText("51");
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        Log.d(TAG,"onResponse");
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            Log.d(TAG,"isSuccessFul");
                            mCurrentWeather = getCurrentDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d(TAG,"how far here");
                                    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), Toast.LENGTH_LONG).show();
        }
        Log.d(TAG,"Main UI code is running!");

    }

    private void updateDisplay() {
        System.out.println("amai wheeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
       mTemperatureLabel.setText( mCurrentWeather.getTemperature()+"");
    }

    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 currentWeather1 = new CurrentWeather();
        currentWeather1.setHumidity(currently.getDouble("humidity"));
        currentWeather1.setTime(currently.getLong("time"));
        currentWeather1.setIcon(currently.getString("icon"));
        currentWeather1.setPrecipChance(currently.getDouble("precipProbability"));
        currentWeather1.setSummary(currently.getString("summary"));
        currentWeather1.setTemperature(currently.getDouble("temperature"));
        currentWeather1.setTimeZone(timezone);

        Log.d(TAG, currentWeather1.getFormattedTime());
        return  currentWeather1;

    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if(networkInfo!=null&&networkInfo.isConnected()){
            isAvailable = true;
            Log.d(TAG,"isAvailable");
        }

        return isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(),"error_dialog");
    }

}

1 Answer

Hiya,

That's a tricky one!

Inside the log in onFailure(), maybe add

Log.e(TAG, "In the onFailure function: " + e);

That might add some clarity to the error? Perhaps e.getStackTrace() would add more details there.

If the code gets to that point you must be connected to the network, so it isn't that, I don't think. You've built a client from the OkHttpClient() constructor, passed that a URL, which looks formatted correctly. You then create a new call and enqueue that off the main thread - this fails.

OkHttp passes the error into the onFailure() method, so let's start there with the suggested log above. We can then drill down into the cause of that error.

Steve.