0

I am making a program and i want to get gps coordinates of my device.The problem is that when locationManager.getLastKnownLocation() is called it returns null.My device runs android 4.4 API 19.

Here is my code:

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener {    

private TextView latituteField;

private TextView longitudeField;
private LocationManager locationManager;
private String provider;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    latituteField = (TextView) findViewById(R.id.TextView02);
    longitudeField = (TextView) findViewById(R.id.TextView04);

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

    provider = LocationManager.GPS_PROVIDER;
    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;
    }
    Location location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
    } else {
        latituteField.setText("Location not available");
        longitudeField.setText("Location not available");
    }
}

/* Request updates at startup */
@Override
protected void onResume() {
    super.onResume();
    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;
    }
    locationManager.requestLocationUpdates(provider, 400, 0, this);
}

/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
    Log.d("location change:", " change1  " );
    int lat = (int) (location.getLatitude());
    int lng = (int) (location.getLongitude());
    latituteField.setText(String.valueOf(lat));
    longitudeField.setText(String.valueOf(lng));
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();

}

@Override
public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider,
            Toast.LENGTH_SHORT).show();
}

}

and this is my Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vaggelis.location">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

What am i doing wrong?

TDG
  • 5,909
  • 3
  • 30
  • 51
E.Volt
  • 235
  • 1
  • 4
  • 8

2 Answers2

0

Follow the below the link and use the code, it's working and tested.

https://medium.com/@ssaurel/getting-gps-location-on-android-with-fused-location-provider-api-1001eb549089

Ananta Prasad
  • 3,655
  • 3
  • 23
  • 35
-1

locationManager.getLastKnownLocation() returns null.

Beacuse everytime it takes time to get last location from your phone.It very old and not good approach.

Google introduces fused api for android. It always return correct value.

I have already answer same question here. Just look at this.If you get any problem then let me know.

Thanks

Community
  • 1
  • 1
Saveen
  • 4,120
  • 14
  • 38
  • 41
  • it says for GoogleApiClient and LocationRequest cannot resolve symbol.Do you know why is that?(My device is running android 4.4 API 19) – E.Volt Mar 10 '17 at 14:56
  • did you add **com.google.android.gms:play-services-location** in your gradle ? – Saveen Mar 11 '17 at 04:39
  • now it is okay thank you.I have two problems: 1) in my manifest file ".service.location.LocationService" says: unresolved calss 'LocatioService , Validates resource references inside Android XML files 2)In my main activity in onCreate method i call startService(new Intent(context, LocationService.class)); like you said .but with what does context needs to be initialized? sorry for the trouble – E.Volt Mar 11 '17 at 10:40
  • I have used **LocationService** class because i need location in background as well. You can do without this also by using **GoogleLocationService** method. Please read my other answer i have mention everything. – Saveen Mar 11 '17 at 11:18