Unable to view current coordinates on button click in android studio
Asked Answered
T

2

1

I am creating an app which will get a user name from DB and print the ID and then on button click it will show the current GPS coordinates. I have implemented it but don't know why its not working.

Here is my Manifest file

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Below is my MainActivity.java

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {


private static final String TAG = "MainActivity";
private TextView tv_lat;
private TextView tv_long;
private Button btn_loc;
private GoogleApiClient googleApiClient;
private Location location;
private LocationManager mLocationManager;
private LocationManager locationManager;

private LocationRequest locationRequest;
private LocationListener locationListener;
private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */

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

    tv_lat = (TextView)findViewById(R.id.tv_lat);
    tv_long = (TextView)findViewById(R.id.tv_long);
    btn_loc = (Button)findViewById(R.id.btn_loc);


    // show location button click event
    btn_loc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                    .addConnectionCallbacks(MainActivity.this)
                    .addOnConnectionFailedListener(MainActivity.this)
                    .addApi(LocationServices.API)
                    .build();


        }
    });

    mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    checkLocation(); //check whether location service is enable or not in your  phone

}

 @Override
public void onConnected(Bundle bundle) {

    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED )
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    startLocationUpdates();

    location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if(location == null)
    {
        startLocationUpdates();
    }
    if (location != null)
    {

    }
    else {
        Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
    }

}

 @Override
public void onConnectionSuspended(int i) {

    Log.i(TAG, "Connection Suspended");
    googleApiClient.connect();

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}

@Override
protected void onStart() {
    super.onStart();
    if (googleApiClient != null) {
        googleApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (googleApiClient.isConnected()) {
        googleApiClient.disconnect();
    }
}

private void startLocationUpdates() {

    // Create the location request
    locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);

    // Request location updates
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED )
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
            locationRequest, this);
    Log.d("reque", "--->>>>");
}

@Override
public void onLocationChanged(Location location) {

    double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    String msg = "Updated Location:  " +
            Double.toString(lattitude) + " , " +
            Double.toString(longitude);

    tv_lat.setText("Latitude is " + lattitude );
    tv_long.setText("Longitude is " + longitude);

    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    // You can now create a LatLng Object for use with maps
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

}

private boolean checkLocation() {

   if(!isLocationEnabled())
    showAlert();

    return isLocationEnabled();
}


private boolean isLocationEnabled() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void showAlert() {

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("Enable Location")
                    .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                            "use this app")
                    .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        }
                    });
            dialog.create().show();
        }
    }
    else {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_LOCATION );
    }
}


}

When i run my app on the my device, below result is shown

enter image description here

When i click on the get location coordinates nothing happens. Also no errors or warnings are shown in logcat.

Update 1

I have moved all the code outside from the button click event

    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    googleApiClient.connect();

    mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

And then debugged it, and i got the below result.

enter image description here

I don't know why the coordinates are not showing :(

Any help would be highly appreciated.

Teston answered 17/2, 2017 at 12:9 Comment(3)
on which android version are you running it? marshmallow or nougat? and have you provided the permissions?Change
I suggest you to go through a tutorial on and download working source code from there. You will find all details there. Gotto this answer, you will find link there. #1513985Archdeacon
@HammadNasir i am running it on marshmallow and yes i have set the permissionsTeston
M
2

When your device is over Android 6.0 Marshmallow, you have to check, that the location permission is allowed in the application settings. You can turn it manually in the settings on or you use the runtime permission library. I've found a very useful library for that: https://github.com/ParkSangGwon/TedPermission

Malefactor answered 21/2, 2017 at 7:20 Comment(6)
It asked me permission and after allowing it, it still doesn't show me the coordinates :(Teston
Do you have tried to restart the app after you granted the location permission?Malefactor
oh yes it's working now, but why it wasn't working on first run?Teston
Do you call the checkLocation Method after the granting of the permission?Malefactor
Can you try to reinstance the GoogleApiClient, when the permission is granted? This would manage the methods like onLocationManage and so on.Malefactor
Let us continue this discussion in chat.Teston
D
1

go to mobile settings-->location settings check whether your mobile GPS service is on or off and turn on if it is off. hope this helps.

Dried answered 17/2, 2017 at 12:34 Comment(1)
My location settings are on in my deviceTeston

© 2022 - 2024 — McMap. All rights reserved.