android location apis : FusedLocationApi.getLastLocation is giving null

I am trying to find last known location of device using GoogleApiClient, So I used fine level access, but getting following exception because location coming is null.

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.kuldeep.location2, PID: 1421
            java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
                at com.example.kuldeep.location2.MainActivity.onConnected(MainActivity.java:51)

                private GoogleApiClient mGoogleApiClient;

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

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

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

                @Override
                protected void onStop() {
                    mGoogleApiClient.disconnect();
                    super.onStop();
                }

                @Override
                public void onConnected(Bundle bundle) {

                    try {
                        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                            mGoogleApiClient);
                        Toast.makeText(this, mLastLocation.getLatitude() + ", " + mLastLocation.getLongitude(), Toast.LENGTH_SHORT);
                    } catch (SecurityException e){
                        e.printStackTrace();
                    }
                }

My manifest file is as follow :

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

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

Answers


First of all, getLastLocation() can be null so you be carefull acessing directly to mLastLocation without a "null" check. In second place, i suggest you to add in your manifest:

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

and then call a LocationRequest.

if(locRequest== null)
{
    locRequest= new LocationRequest();
    locRequest.setInterval( interval );
    locRequest.setFastestInterval( fastestInterval );
    locRequest.setPriority( priority );

    LocationServices.FusedLocationApi.requestLocationUpdates(yourGoogleApiClient, locRequest, this);
}

Using GoogleApiClient find a CurrentLocation like these:

private GoogleApiClient googleApiClient;
private Location mLastLocation;

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

                    isCheckLocationServiceisOn(context);

                    if(googleApiClient == null) {
                    googleApiClient = new GoogleApiClient.Builder(this)
                   .addConnectionCallbacks(this)
                   .addOnConnectionFailedListener(this)
                   .addApi(LocationServices.API)
                   .build();
        }

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

                @Override
                protected void onStop() {
                    mGoogleApiClient.disconnect();
                    super.onStop();
                }


               @Override
               protected void onResume() {
                  super.onResume();
                  isCheckLocationServiceisOn(context); 
                }

              @Override
              public void onConnected(Bundle arg0) {

             if(googleApiClient.isConnected()) {
              mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

            if (mLastLocation != null) {
                System.out.println("latiTude....."+ String.valueOf(mLastLocation.getLatitude()));
                System.out.println("longiTude....."+ String.valueOf(mLastLocation.getLongitude()));
            }   
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        System.out.println("onConnectionFailed...."+ arg0.toString());
    }


    @Override
    public void onConnectionSuspended(int arg0) {
        System.out.println("onConnectionSuspended...."+ arg0);
    }  

Add Permission in manifest:

    <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" /> 

Here,

Implements ConnectionCallbacks, OnConnectionFailedListener interface for that supported override methods they must be com.google.android.gms.common.api.GoogleApiClient package.

MUST REMEMBER:

Wi-Fi and GSM and GPS is must be on in device if not then generate these kind of error in onConnected()

I give you code to check & open location service also:

public static void isCheckLocationServiceisOn (final Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        boolean gps_enabled = false;
        boolean network_enabled = false;

        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } 
        catch(Exception ex) {}

        try {
            network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }
        catch(Exception ex) {}

        if(!gps_enabled && !network_enabled) {
            // notify user
            AlertDialog.Builder dialog = new AlertDialog.Builder(context);
            dialog.setMessage("Location Services Disabled. \n Please enable location services.");

            dialog.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        Intent myIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        context.startActivity(myIntent);
                        //get gps
                    }
                });

            dialog.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {

                    @Override                                                                                                                                                                       
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {


                    }
                });
            dialog.show();      
        }       
    }

Need Your Help

raw depth data to text kinect v1.0 C#

c# text kinect depth

I've been searching the internet and I haven't had any luck. I'm using an Xbox Kinect with the Kinect SDK v1.0. I want to take the raw depth data and convert it into a text document so I can use the

[Log4j2]: Programmatically turn off logging for specific Java packages

java logging log4j2

I am using the following code to programatically configure my logging config: