Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

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 :))

Code:

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;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    final GPSTracker gpsTracker = new GPSTracker(this);

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

            } else {
            gpsTracker.showSettingsAlert();
            }
        }
    });
    getForecast(gpsTracker);
    }


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() {
                @Override
                public void onFailure(Request request, IOException e) {
                    alertUserAboutError();
                }

                @Override
                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() {
                                @Override
                                public void run() {
                                    if (gpsTracker.getIsGPSTrackingEnabled()) {
                                        updateDisplay(gpsTracker);
                                    } else {
                                        gpsTracker.showSettingsAlert();
                                    }
                                }
                            });

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


}

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() + "");
        mTimeLabel.setText(currently.getFormattedTime());
        mHumidityValue.setText(currently.getHumidity() + "%");
        mPrecipValue.setText(currently.getPrecipChance() + "%");
        mSummaryLabel.setText(currently.getSummary());
        mWindSpeedValue.setText(currently.getWindSpeed() + "");
        Drawable drawable = getResources().getDrawable(currently.getBackgroundId());
        mRelativeLayout.setBackground(drawable);
}

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();
    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
    currentWeather.setSummary(currently.getString("summary"));
    currentWeather.setTemperature(currently.getDouble("temperature"));
    currentWeather.setWindSpeed(currently.getDouble("windSpeed"));
    currentWeather.setTimeZone(timezone);
    currentWeather.setBackgroundId(currently.getString("icon"));

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

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