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) Hooking Up the Model to the View Wrapping Up

Brendan Milton
Brendan Milton
9,050 Points

Attempting to add location service, project loads but doesn't appear to be doing it via gps. Can anyone advise??

Attempting to add location service, project loads but doesn't appear to be logging the data via gps. Can anyone advise to whats wrong with my code?

public class MainActivity extends ActionBarActivity {

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

private CurrentWeather mCurrentWeather;
GPSTracker gps = new GPSTracker(this);

// Butterknife comparable way to set up member variables
@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 = gps.getLatitude(); //37.8267;
    final double longitude = gps.getLongitude(); //-122.423;

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

    getForecast(latitude, longitude);

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


private void getForecast(double latitude, double longitude) {
    String apiKey = "2b415d1a17a053e17c95b044651c9dc8";

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

        // Weather Loading refresh Data
        toggleRefresh();

        // JSON Client to import data
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(forecastUrl)
                .build();

        // Call Request for JSON data
        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 {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });
                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mCurrentWeather = getCurrentDetails(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, getString(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() {
    mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
    mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
    mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
    mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "");
    mSummaryLabel.setText(mCurrentWeather.getSummary());

    Drawable drawable = ContextCompat.getDrawable(this, mCurrentWeather.getIconId());
    mIconImageView.setImageDrawable(drawable);
}

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

    CurrentWeather currentWeather = new CurrentWeather();
    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 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");
}

}

public class GPSTracker extends Service implements LocationListener {

//http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/ private final Context mContext;

// flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; boolean canGetLocation = false;

Location location; double latitude; double longitude;

// The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 300; // 300 meters

// The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 60; // 60 minutes

// Declaring a Location Manager protected LocationManager locationManager;

public GPSTracker(Context context) { this.mContext = context; getLocation(); }

public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE);

     // getting GPS status
     isGPSEnabled = locationManager
             .isProviderEnabled(LocationManager.GPS_PROVIDER);

     // getting network status
     isNetworkEnabled = locationManager
             .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

     if (!isGPSEnabled && !isNetworkEnabled) {
        // no network provider is enabled
     } else {
        this.canGetLocation = true;
        // First get location from Network Provider
        if (isNetworkEnabled) {
           locationManager.requestLocationUpdates(
                   LocationManager.NETWORK_PROVIDER,
                   MIN_TIME_BW_UPDATES,
                   MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
           Log.d("Network", "Network");
           if (locationManager != null) {
              location = locationManager
                      .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
              if (location != null) {
                 latitude = location.getLatitude();
                 longitude = location.getLongitude();
              }
           }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled) {
           if (location == null) {
              locationManager.requestLocationUpdates(
                      LocationManager.GPS_PROVIDER,
                      MIN_TIME_BW_UPDATES,
                      MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
              Log.d("GPS Enabled", "GPS Enabled");
              if (locationManager != null) {
                 location = locationManager
                         .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                 if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                 }
              }
           }
        }
     }

  } catch (Exception e) {
     e.printStackTrace();
  }

  return location;

}

@Override public void onLocationChanged(Location location) { }

@Override public void onProviderDisabled(String provider) { }

@Override public void onProviderEnabled(String provider) { }

@Override public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override public IBinder onBind(Intent arg0) { return null; }

public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); }

  // return latitude
  return latitude;

}

public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); }

  // return longitude
  return longitude;

}

public boolean canGetLocation() { return this.canGetLocation; }

public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

  // Setting Dialog Title
  alertDialog.setTitle("GPS is settings");

  // Setting Dialog Message
  alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

  // Setting Icon to Dialog
  //alertDialog.setIcon(R.drawable.delete);

  // On pressing Settings button
  alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog,int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(intent);
     }
  });

  // on pressing cancel button
  alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
     }
  });

  // Showing Alert Message
  alertDialog.show();

}

public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } }

2 Answers

Hi Brendan,

There are a few posts about this in this forum. Here is one I started - there have been a few more like this one.

My app works from the location perspective but I never did get round to finishing it to how I want it to look. Feel free to look at my code here.

Hope that helps.

Steve.

Brendan Milton
Brendan Milton
9,050 Points

Thanks Steve! i'll look it up!