0

Now I have a strange problem. I have FusedLocationApi code.check it.I'm mentioning only related codes :

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

        GoogleApiClient mGoogleApiClient;
        Location mLastLocation;



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


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


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




     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    double latitude = mLastLocation.getLatitude();
                    double longitude = mLastLocation.getLongitude();

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

        }

            }

Now the problem is,this code is working perfectly for this activity.But when I'm writing the same code for other activity of the same project,mLastLocation is returning null and I am getting a java.lang.NullPointerException.

only difference for that class is that there I'm implementing OnMapReadyCallback also.Does it make any difference?

I've read all the Q&A on this topic but not getting any help. What's the mistake from my side?

Tuhin Subhra
  • 356
  • 5
  • 17

1 Answers1

0

onCreate method called first then followed by onStart. So in your case if mGoogleApiClient is not connected on create it will return null.move this code from onCreate to onStart

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                double latitude = mLastLocation.getLatitude();
                double longitude = mLastLocation.getLongitude();

i will do something like this onStart

if(mGoogleApiClient.isConnected()){
        // check for last location
    }else{
        mGoogleApiClient.connect();
        //check for last location
    }
Hareesh
  • 6,770
  • 4
  • 33
  • 60