0

I am working on an application where I need to fetch the users current location. I am following this tutorial to achieve my goal http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/. This code works perfectly for me but there is some delay in fetching the co-ordinates. I want to show a progress dialog until the co-ordinates are fetched.

I found a similar question asked here Android show progress dialog while waiting for location

But I don’t follow the accepted answer. I tried it but it didn’t work for me …

My Problem :

1.When the application first starts with GPS Setting on, the ProgressDialog is infinite. That is, it doesn't dismiss.

  1. Once the locations co-ordinates are found, the application crashes.

Errors :

For the 2nd problem is NullPointerException. Somehow the application is not able to find the dialog at the main activity. (inside onLocationChanged()).

Please help.

My code :

Main Activity :-

public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;
    ProgressDialog dialog;
    TextView tv_addressView;
    Location loc;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv_addressView = (TextView)findViewById(R.id.tv_address);
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

    @Override
public void onClick(View arg0) 
{
if(loc == null)
                    {
                            dialog = ProgressDialog.show(
AndroidGPSTrackingActivity.this,
"Getting Co-ordinates",
"Please Wait ...");
                    }

             });
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        gps = new GPSTracker(getApplicationContext(),AndroidGPSTrackingActivity.this);
        loc = gps.getLocation();
        if(gps.canGetLocation())
         {
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();
            Log.d("Got","Lat = "+latitude+"\nLong = "+longitude);
         }
        else
        {
                    gps.showSettingsAlert();
        }

    }

    public void dismissDialog()
    {
        if(dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void upDateUI(String result)
    {
        tv_addressView.setText(result);
    }

}

GPSTracker.java

public class GPSTracker extends Service implements LocationListener {

        ProgressDialog dialog;
    private final Context mContext;
boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
    double latitude; // latitude
    double longitude; // longitude
AndroidGPSTrackingActivity callingActivity;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;


    public GPSTracker(Context context, AndroidGPSTrackingActivity activity) 
{
        this.mContext = context;
                this.callingActivity = activity;
            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;
                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;
    }

    public Location returnLocation()
    {
        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            //dialog.dismiss();
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation()
    {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(callingActivity);

        // 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?");

        // 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);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                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();
    }

    @Override
    public void onLocationChanged(Location location) {


       callingActivity.dismissDialog();

    }

    @Override
    public void onProviderDisabled(String provider) {
        stopUsingGPS();
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

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

}
Community
  • 1
  • 1
Partha Chetry
  • 136
  • 1
  • 9
  • Why extending `service` in `GPSTracker` class? – ρяσѕρєя K Jun 26 '15 at 16:07
  • Before `mContext.startActivity(intent);` line add `dialog.cancel();` to close Alert before starting Setting Activity – ρяσѕρєя K Jun 26 '15 at 16:10
  • @ρяσѕρєяK :- i guess that would dismiss the progressdialog before showing the Settings menu. But say the GPS is on when the application starts. In that case the mContext.startActivity(intent) will never be called. In this case where do I put the dialog.dismiss() – Partha Chetry Jun 26 '15 at 16:29
  • As noted by @ρяσѕρєя K the tutorial code you used has problems. GPSTracker is derived from Service, but is never started by a call to startService() in the activity. If it truly needs to run as a service, changes are needed. If GPSTracker were to be correctly implemented as a true Service, it is not safe to pass an Activity in the constructor and save it as a member. The activity could be stopped and destroyed while the service continues running, leaving you with an invalid reference. – Bob Snyder Jun 26 '15 at 16:31
  • @qbix :- great !!! totally makes sense ... can you guide me in the right direction please. A tutorial will be great !!!! Also below there is a code posted which I would like to try. But again ... the code works perfectly in the current form. The problem is while displaying the ProgressDialog. – Partha Chetry Jun 26 '15 at 16:34
  • Try the solution offered by @Kadir. Your GPSTracker class probably does not need to implemented as a Service. – Bob Snyder Jun 26 '15 at 16:46
  • @qbix :- the solution below works fine ... get the location that is ... but it doesn't address my issue which is "No Progress Dialog while getting Co-ordinates" – Partha Chetry Jun 26 '15 at 17:32

1 Answers1

0

Try this

public final class GPSTracker implements LocationListener {

private final Context mContext;

// flag for GPS status
public boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

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

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

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

/**
 * Function to get the user's current location
 * 
 * @return
 */
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

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

        Log.v("isGPSEnabled", "=" + isGPSEnabled);

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

        Log.v("isNetworkEnabled", "=" + isNetworkEnabled);

        if (isGPSEnabled == false && isNetworkEnabled == false) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                location=null;
                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) {
                location=null;
                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;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
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?");

    // 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();
}

@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) {
}

}