Search code examples
androidgoogle-apigeolocation

Erron Getting the Last Known Location Using GoogleApiClient in Android


Trying to get last location of device

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

GoogleApiClient mGoogleApiClient;
TextView textView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    textView = (TextView) findViewById(R.id.text_view);
    setContentView(R.layout.activity_main);
    if (mGoogleApiClient == null) {
        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(@Nullable 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;
    }
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        double lat = mLastLocation.getLatitude();

        textView.setText(String.valueOf(lat));          
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

These are the errors

09-01 12:16:06.385 24018-24018/mzkhan.assignmenttask E/AndroidRuntime: FATAL EXCEPTION: main Process: mzkhan.assignmenttask, PID: 24018 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at mzkhan.assignmenttask.MainActivity.onConnected(MainActivity.java:70) at com.google.android.gms.common.internal.zzl.zzo(Unknown Source) at com.google.android.gms.internal.zzpy.zzm(Unknown Source) at com.google.android.gms.internal.zzpw.zzapp(Unknown Source) at com.google.android.gms.internal.zzpw.onConnected(Unknown Source) at com.google.android.gms.internal.zzqa.onConnected(Unknown Source) at com.google.android.gms.internal.zzpp.onConnected(Unknown Source) at com.google.android.gms.common.internal.zzk$1.onConnected(Unknown Source) at com.google.android.gms.common.internal.zzd$zzj.zzasd(Unknown Source) at com.google.android.gms.common.internal.zzd$zza.zzc(Unknown Source) at com.google.android.gms.common.internal.zzd$zza.zzv(Unknown Source) at com.google.android.gms.common.internal.zzd$zze.zzasf(Unknown Source) at com.google.android.gms.common.internal.zzd$zzd.handleMessage(Unknown Source) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5938) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)


Solution

  • Please look at the code changes below. You have initiated textview before setting context view in onCreate, so while accessing text view it is returning NPE.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text_view); // swapped this line
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        }
    }