4

I am developing my first Android app which should get the latitude and longitude of an android device and send it via a web service to a template document.

I followed the guide of getting the location from http://developer.android.com/training/location/retrieve-current.html.

This is the code from my .java class:

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class GetLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private GoogleApiClient mGoogleApiClient;
    EditText textLat;
    EditText textLong;
    EditText lat;
    EditText lon;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_location);

        textLat = (EditText) findViewById(R.id.latitude);
        textLong = (EditText) findViewById(R.id.longitude);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    private boolean isGPSEnabled() {
        LocationManager cm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return cm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            lat.setText(String.valueOf(mLastLocation.getLatitude()));
            lon.setText(String.valueOf(mLastLocation.getLongitude()));
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public void onButtonClick(View v){
        if(v.getId() == R.id.getGpsLocation){
            if(!isGPSEnabled()){
                new AlertDialog.Builder(this)
                        .setMessage("Please activate your GPS Location!")
                        .setCancelable(false)
                        .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(i);
                            }
                        })
                        .setNegativeButton("Cancel", null)
                        .show();
            } else {
                textLat.setText(String.valueOf(lat));
                textLong.setText(String.valueOf(lon));
            }

        }
    }


}

I don't get any errors but when I am tapping the button which should get the coordinates, I get 'null' text in both views.

I also have included permissions for internet, access fine and coarse location.

Thanks in advance!

RayzaN
  • 41
  • 1
  • 2
  • 6
  • I doesn't look like you actually ever connected to the `mGoogleApiClient` by calling `mGoogleApiClient.connect` in onStart as stated in the docs. I'm assuming you never actually get a callback to `onConnected` so you have no data set. You can easily test that if you put a log in `onConnected` – cbw Jan 06 '17 at 06:52

4 Answers4

2

I have written detailed tutorial covering this topic here on demonuts.com.You can find more description here and also you can download whole demo source code for better understanding.

First of all, put this in gradle file

 compile 'com.google.android.gms:play-services:9.0.2'

then implement necessary interfaces

public class MainActivity  extends BaseActivitiy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

declare instances

  private GoogleApiClient mGoogleApiClient;
  private Location mLocation;
  private LocationManager locationManager;
  private LocationRequest mLocationRequest;

put this in onCreate()

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

At last, override necessary methods

 @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();
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLocation == null){
            startLocationUpdates();
        }
        if (mLocation != null) {
            double latitude = mLocation.getLatitude();
            double longitude = mLocation.getLongitude();
        } else {
            // Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
        }
    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_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(mGoogleApiClient,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        mGoogleApiClient.connect();
    }

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

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    @Override
    public void onLocationChanged(Location location) {

    }

Don't forget to start GPS in your device before running app.

Parsania Hardik
  • 4,593
  • 1
  • 33
  • 33
1

You need to define LocationListener .

public class MainActivity extends Activity implements LocationListener{
    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;
    TextView txtLat;
    String lat;
    String provider;
    protected String latitude,longitude; 
    protected boolean gps_enabled,network_enabled;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtLat = (TextView) findViewById(R.id.textview1);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    @Override
    public void onLocationChanged(Location location) {
        txtLat = (TextView) findViewById(R.id.textview1);
        txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d("Latitude","disable");
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d("Latitude","enable");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Latitude","status");
    }
}

And need to give below permission :

ACCESS_COARSE_LOCATION : It is used when we use network location provider for our Android app.

ACCESS_FINE_LOCATION : It is providing permission for both providers.

INTERNET : permission is must for the use of network provider.

Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
KishuDroid
  • 5,411
  • 4
  • 30
  • 47
0

Here is a working example of user location:

https://github.com/keithweaver/Android-Samples/tree/master/Location

Keith
  • 637
  • 1
  • 8
  • 23
0

you can get current location by using these simple steps

give internet permission in manifest file

give ACCESS_FINE_LOCATION permission in manifest

public class MainActivity extends AppCompatActivity implements LocationListener {
Button button_location,button_locationinMap,Last_locationUser,shareBtn;
TextView textView_location;
LocationManager locationManager;
ProgressBar SHOW_PROGRESS;
String address;
double latitude;
double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button_location=findViewById(R.id.button_location);
    textView_location=findViewById(R.id.text_location);
    Last_locationUser=findViewById(R.id.Last_locationUser);
    SHOW_PROGRESS=findViewById(R.id.SHOW_PROGRESS);
    shareBtn=findViewById(R.id.shareBtn);
    button_locationinMap=findViewById(R.id.button_locationinMap);
    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(MainActivity.this,new String[]
                {
                        Manifest.permission.ACCESS_FINE_LOCATION},100);
    }
    shareBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String uri = "https://www.google.com/maps/?q="+latitude+","+longitude ;
            Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,  uri);
            startActivity(Intent.createChooser(sharingIntent, "Share in..."));
        }
    });
    button_location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getLocation();
            SHOW_PROGRESS.setVisibility(View.VISIBLE);
        }
    });
    button_locationinMap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(MainActivity.this,GoogleMapActivity.class);
            startActivity(intent);
        }
    });
    Last_locationUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(MainActivity.this,UserLastLocation.class);
            startActivity(intent);
        }
    });
}
@SuppressLint("MissingPermission")
private void getLocation() {
    try
    {
        locationManager=(LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,50000,0,MainActivity.this);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
@Override
public void onLocationChanged(@NonNull Location location) {
    Toast.makeText(this, ""+location.getLatitude()+","+location.getLongitude(), Toast.LENGTH_SHORT).show();

    try {
        Geocoder geocoder=new Geocoder(MainActivity.this, Locale.getDefault());
        List<Address> addresses=geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
        address=addresses.get(0).getAddressLine(0);
        textView_location.setText(address);
        SHOW_PROGRESS.setVisibility(View.GONE);
        textView_location.setVisibility(View.VISIBLE);

        latitude=location.getLatitude();
        longitude=location.getLongitude();

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}
@Override
public void onProviderEnabled(@NonNull String provider) {

}

@Override
public void onProviderDisabled(@NonNull String provider) {
}

}

Raiyan Shahid
  • 49
  • 1
  • 3