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!

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


Onur Çevik
Onur Çevik
2,390 Points

Dynamic Location Retrieving Problem In My Weather App

Hi everyone.

So I decided to do some changes on the Stormy app Ben walked us through, and add a dynamic location instead of the hard-coded one. Everything's fine until user goes to Settings, Enables Location and returns to the app. When he/she returns, they should get their locations updated, right? At least that's what I hoped. Waiting, and refreshing several times does not solve the problem. User has to close and reopen the app to get Location info while they should be getting the Location info once they enable Location. I'm providing the code below. Note that everything other than this works fine. Check the if-else statement of getForecast() method, where app checks for the network, proceeds if network is available, pops a dialog if not, and when you go to Settings and enable mobile data through that dialog, app gets the Forecast info, without needing to close-reopen app. In onRefresh() method I tried to do the same if-else statement method, followed by a gpsTracker.showSettingsAlert(); call so that user can enable Location and refresh the app to get data. Dialog pops up, user goes to Settings and enables Location, comes back to the app but app does not proceed and stays the same. I know it's a bit long, but I would really appreciate a help. Thanks in advance. (Also I tried my best to use the Code View function correctly, but wouldn't mind an edit :))


public class MainActivity extends AppCompatActivity {

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

@Bind(R.id.timeLabel) TextView mTimeLabel;
@Bind(R.id.tempLabel) TextView mTempLabel;
@Bind(R.id.humidityValue) TextView mHumidityValue;
@Bind(R.id.precipValue) TextView mPrecipValue;
@Bind(R.id.summaryLabel) TextView mSummaryLabel;
@Bind(R.id.windSpeedValue) TextView mWindSpeedValue;
@Bind(R.id.relativeLayout) RelativeLayout mRelativeLayout;
@Bind(R.id.container) SwipeRefreshLayout mSwipeRefreshLayout;
@Bind(R.id.locationLabel) TextView mLocationLabel;

double latitude;
double longitude;
protected void onCreate(Bundle savedInstanceState) {
    final GPSTracker gpsTracker = new GPSTracker(this);

    mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                public void run() {
            }, 2000);
            if (gpsTracker.getIsGPSTrackingEnabled()){

            } else {

private void getForecast(final GPSTracker gpsTracker) {

        latitude = gpsTracker.getLatitude();
        longitude = gpsTracker.getLongitude();
        String apiKey = "7d22cdb138cd70f2e9e8d2006cd0461c";
        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() {
                public void onFailure(Request request, IOException e) {

                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            mForecast = parseForecastDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (gpsTracker.getIsGPSTrackingEnabled()) {
                                    } else {

                        } else {
                    } catch (IOException | JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
        } else {


private void updateDisplay(GPSTracker gpsTracker) {

    Currently currently = mForecast.getCurrently();

        String area = gpsTracker.getSubLocality(this);
        String city = gpsTracker.getAdminArea(this);
        String country = gpsTracker.getCountryName(this);
        mLocationLabel.setText(area + "\n" + city + ", " + country);
        mTempLabel.setText(currently.getTemperature() + "");
        mHumidityValue.setText(currently.getHumidity() + "%");
        mPrecipValue.setText(currently.getPrecipChance() + "%");
        mWindSpeedValue.setText(currently.getWindSpeed() + "");
        Drawable drawable = getResources().getDrawable(currently.getBackgroundId());

private Currently getCurrentlyDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject currently = forecast.getJSONObject("currently");

    Currently currentWeather = new Currently();

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

    return currentWeather;

 private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager)
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()){
        isAvailable = true;
    return isAvailable;