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 Android Lists and Adapters (2015) Using Parcelable Data Retrieving Parcelable Data

Sahit penmatcha
Sahit penmatcha
4,555 Points

App STOPS when daily button clicked.. no error in Android Monitor

when i click the 7 day button, the app crashes and no error shows up in the Android Monitor

package com.example.sahitpenmatcha.stormy.ui;

import android.content.Context; import android.content.Intent; 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.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast;

import com.example.sahitpenmatcha.stormy.R; import com.example.sahitpenmatcha.stormy.weather.Current; import com.example.sahitpenmatcha.stormy.weather.Day; import com.example.sahitpenmatcha.stormy.weather.Forecast; import com.example.sahitpenmatcha.stormy.weather.Hour;

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

import java.io.IOException;

import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";

private Forecast mForecast;

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

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

    mProgressBar.setVisibility(View.INVISIBLE);

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

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

    getForecast(latitude, longitude);
    //calling the request
    //seeing if the call was succesful and if there were any exceptions
    //if there were exceptions, 'catch' them

    Log.d(TAG, "Main UI Code is running!");
}

private void getForecast(double latitude, double longitude) {
    String apiKey = "5937322d4a925781a3eb76a63858e0bd";
    String forecastURL = "https://api.forecast.io/forecast/" + apiKey +"/" +latitude +"," +longitude;

    if (isNeworkAvailable()) {
        toggleRefresh();

        OkHttpClient client = new OkHttpClient();
        //creating the client that will handle the call
        Request request = new Request.Builder().url(forecastURL).build();
        //creating the request

        Call call = client.newCall(request);
        call.enqueue(new Callback() //executing the call and putting it in a queue...doesnt execute immediately(background thread)
        {
            @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();
                    //calling the request and retrieving the request
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mForecast = parseForecastDetails(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, 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() {

    Current current = mForecast.getCurrent();
    mTemperatureLabel.setText(current.getTemperature()+"");
    mTimeLabel.setText("At " +current.getFormattedTime() + " it will be");
    mHumidityValue.setText(current.getHumidity()+"");
    mPrecipValue.setText(current.getPrecipChance() + "%");
    mSummaryLabel.setText(current.getSummary());
    Drawable drawable = getResources().getDrawable(current.getIconId());
    mIconImageView.setImageDrawable(drawable);
}

private Forecast parseForecastDetails(String jsonData) throws JSONException{
    Forecast forecast = new Forecast();

    forecast.setCurrent(getCurrentDetails(jsonData));
    forecast.setHourlyForecast(getHourlyForecast(jsonData));
    forecast.setDailyForecast(getDailyForecast(jsonData));
    return forecast;
}

private Day[] getDailyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject daily = forecast.getJSONObject("daily");
    JSONArray data = daily.getJSONArray("data");

    Day[] days = new Day[data.length()];

    for (int i = 0; i < data.length(); i++){
        JSONObject jsonDay = data.getJSONObject(i);
        Day day = new Day();

        day.setSummary(jsonDay.getString("summary"));
        day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
        day.setIcon(jsonDay.getString("icon"));
        day.setTime(jsonDay.getLong("time"));
        day.setTimezone(timezone);

        days[i] = day;
    }
    return days;
}

private Hour[] getHourlyForecast(String jsonData) throws JSONException{
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject hourly = forecast.getJSONObject("hourly");
    JSONArray data = hourly.getJSONArray("data");

    Hour[] hours = new Hour[data.length()];

    for (int i = 0; i < data.length(); i++){
        JSONObject jsonHour = data.getJSONObject(i);
        Hour hour = new Hour();

        hour.setSummary(jsonHour.getString("summary"));
        hour.setTemperature(jsonHour.getDouble("temperature"));
        hour.setIcon(jsonHour.getString("icon"));
        hour.setTime(jsonHour.getLong("time"));
        hour.setTimezone(timezone);

        hours[i] = hour;
    }
    return hours;
}


private Current 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");

    Current currentWeather = new Current();
    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"));
    currentWeather.setTimeZone(timezone);

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

    return currentWeather;
}


private boolean isNeworkAvailable() {
    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"); //second parameter is just a tag to id it
}

@OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
    Intent intent = new Intent(this, DailyForecastActivity.class);
    intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
    startActivity(intent);
}

}

Deividas Strioga
Deividas Strioga
12,851 Points

Hey, there must be some error in the log, check it again or post it here. Also try going through debug to find it.

1 Answer

Jacob Bergdahl
Jacob Bergdahl
29,118 Points

There is always an error in the log when the app crashes :) Sometimes, you might have to click on "no filter" in the upper right corner of the log to see it. Please post the error message and I'll see what I can do!

Sahit penmatcha
Sahit penmatcha
4,555 Points

07-03 09:53:25.953 1432-3387/? W/ActivityManager: Force finishing activity com.example.sahitpenmatcha.stormy/.ui.MainActivity 07-03 09:53:27.653 1432-2165/? D/PackageManager: getComponentMetadataForIconTray : com.example.sahitpenmatcha.stormy.ui.MainActivity does not exist in mServices 07-03 09:53:27.653 1432-2165/? D/PackageManager: getComponentMetadataForIconTray : com.example.sahitpenmatcha.stormy.ui.MainActivity does not exist in mProviders 07-03 09:53:27.653 1432-2165/? D/PackageManager: getComponentMetadataForIconTray : com.example.sahitpenmatcha.stormy.ui.MainActivity does not exist in mReceivers 07-03 09:53:35.953 1432-1532/? W/ActivityManager: Activity destroy timeout for ActivityRecord{c13d338 u0 com.example.sahitpenmatcha.stormy/.ui.MainActivity t6518 f}

Hi! This is the error I get.