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

Why is this not working?

I was making a weather app for Android, there were no errors nor warnings but It is not updating the User Interface for the app.

This is my Main Activity:

//This is the package name 'everingapplications.rain_gig'
package everingapplications.rain_gig;

//Importing the necessary
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

//Importing the Wi-Fi files
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;


//Importing the JSON files
import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;

//Importing ButterKnife
import butterknife.ButterKnife;
import butterknife.InjectView;

//Importing the Toast Widget
import static android.widget.Toast.LENGTH_LONG;


//Declaring the class
public class MainActivity extends AppCompatActivity {

    //Declaring the TAG String
    public static final String TAG = MainActivity.class.getSimpleName();


    //Declaring CurrentWeather
    private CurrentWeather mCurrentWeather;

    //Inject views using ButterKnife
    @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;


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


        double longitude = 37.3667;
        double latitude = 79.2667;



        getForecast(latitude, longitude);

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

    }

    private void getForecast(double latitude, double longitude) {
        String apiKEY = "1fc52007d735d76038460b34d37fbe16";
        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) {

                }

                private void updateDisplay() {
                    mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "°");
                    mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + "it will be: ");
                    mHumidityValue.setText("Humidity: " + mCurrentWeather.getHumidity() + "");
                    mPrecipValue.setText("Precip. Chances: " + mCurrentWeather.getPrecipChance() + "");
                    mSummaryLabel.setText(mCurrentWeather.getSummary() + "");
                }


                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        android.util.Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        android.util.Log.e(TAG, "Exception caught: ", e);
                    } catch (JSONException ignored) {

                    }
                }
            });
        } else {
            Toast.makeText(this, "No Network Connection.", LENGTH_LONG).show();
        }
    }




    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        android.util.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("precipProbabiltiy"));
        currentWeather.setSummary(currently.getString("summary"));
        currentWeather.setTemperature(currently.getDouble("temperature"));
        currentWeather.setmTimeZone(timezone);
        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");
    }

}

1 Answer

In getCurrentDetails() you have a typo on the line:

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

you misspelled "Probability" which will cause it to throw a JSONException. (It's also a good idea to log any JSONException in the catch statement so you can see where the error is happening.)