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) Concurrency and Error Handling Configuring the Alert Dialog

Mahmoud Tokura
Mahmoud Tokura
789 Points

My error alert doesn't pop up, app just crashes.

I followed all your steps but my error alert doesn't pop up, the app just crashes on start up. Also my Log messages don't seem to appear in Log.

4 Answers

I have similar problems. Just go to File?Invalidate caches and restart

I'm assuming it's an Android Studio bug

Mahmoud Tokura
Mahmoud Tokura
789 Points

i just tried it bro, still not working. thanks for the reply though.

Could you please copy/paste your code? Maybe I can have a look then.

Mahmoud Tokura
Mahmoud Tokura
789 Points

I used the same alert code i have on my other apps but that also didn't work, see it commented bellow.

package com.appsobey.stormy;

import android.app.AlertDialog; import android.app.DownloadManager; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Drawable; 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.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; 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;

import butterknife.ButterKnife; import butterknife.InjectView;

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

private 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;
@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 logitude = -122.423;

    mRefreshImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getForcast(latitude,logitude);
        }
    });

    getForcast(latitude,logitude);
    Log.d(TAG,"Main thread is running!!!");

}

private void getForcast(double latitude, double logitude) {
    String apiKey ="ace17aa2966c706e3ceec37c46f0eefa";

    String forcastURL = "https://api.forecast.io/forecast/"+ apiKey + "/" + latitude + "," +logitude;
    if(isNetworkAvailable()) {
        ToggleRefresh();

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

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToggleRefresh();
                    }
                });
                AlertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {

                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mCurrentWeather = getCurrentDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToggleRefresh();
                            }
                        });
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                UpdateDisplay();
                            }
                        });


                    } else {
                        AlertUserAboutError();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "exceptions caught", e);
                }
                catch (JSONException e) {
                    Log.e(TAG, "exceptions caught", e);
                }
            }
        });
    }else {
        Toast.makeText(this, getString(R.string.error_noNetwork), 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.getTemprature()+"");
    mTimeLabel.setText("At "+ mCurrentWeather.getFormatedTime()+ " it will be");
    mHumidityValue.setText(mCurrentWeather.getnHumididty()+ "");
    mPrecipValue.setText(mCurrentWeather.getPrecipChance()+"%");
    mSummaryLabel.setText(mCurrentWeather.getSummery());
    Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
    mIconImageView.setImageDrawable(drawable);
}

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

    JSONObject currently = forcast.getJSONObject("currently");
    CurrentWeather currentWeather = new CurrentWeather();
    currentWeather.setnHumididty(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setIcon(currently.getString("icon"));
    currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
    currentWeather.setSummery(currently.getString("summary"));
    currentWeather.setTemprature(currently.getDouble("temperature"));
    currentWeather.setTimeZone(timezone);

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

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

// The alert code i use for my other apps also didnt work, see bellow private void AlertUserAboutError() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("error_dialog"); builder.setTitle("Sorry"); builder.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss();

        }

    });
    AlertDialog dialog = builder.create();
    dialog.show();

}

}