0

First of all sorry for asking this silly question. As i am new to android so i am trying to make an app in which first there will dialog box open for asking the permission to turn on the GPS like google maps or ola do. Then after that i wanted to get user latitude and longitude but unfortunately i tried and search so many links but i didn't get right solution. so can anyone help me out.

My Code is :

public class GpsPlaceSearch extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener 
{
    Activity context;
    GoogleApiClient googleApiClient, getGoogleApiClient;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    LocationRequest locationRequest1;

    Location location;
    private double currentLatitude;
    private double currentLongitude;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;

    public GpsPlaceSearch(){

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps_place_search);
        getGoogleApiClient = new GoogleApiClient.Builder(this)
                class will handle connection stuff
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)
                .build();

        locationRequest1=locationRequests();
    }

    public GpsPlaceSearch(Activity context){
        this.context=context;
        googleApiClient=getInstance();
        if (googleApiClient!=null){
            settingsrequest();

            googleApiClient.connect();
        }
    }

    public LocationRequest locationRequests(){
        LocationRequest locationRequest=LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        return locationRequest;
    }

    public GoogleApiClient getInstance(){
        GoogleApiClient mGoogleApiClient=new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        return mGoogleApiClient;
    }

    public void settingsrequest(){
        Log.e("settingsrequest","Comes");

        locationRequest1=locationRequests();
        LocationSettingsRequest.Builder builder=new LocationSettingsRequest.Builder().addLocationRequest(locationRequest1);

        builder.setAlwaysShow(true);
        final PendingResult<LocationSettingsResult> result= LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                Status status=result.getStatus();
                LocationSettingsStates states=result.getLocationSettingsStates();
                switch (status.getStatusCode()){
                    case LocationSettingsStatusCodes.SUCCESS:

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try{
                            status.startResolutionForResult(context,REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        break;
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onConnected(Bundle bundle) {
        location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient);
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},108);
            LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient,locationRequest1,this);

        }
        else {

            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " AND " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        if (connectionResult.hasResolution()){
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
        else {
            Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Activity mActivity=this;
        GpsPlaceSearch gpsPlaceSearch=new GpsPlaceSearch(mActivity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Now lets connect to the API
        getGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (getGoogleApiClient.isConnected()){
            LocationServices.FusedLocationApi.removeLocationUpdates(getGoogleApiClient,this);
            getGoogleApiClient.disconnect();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LocationSettingsStates states=LocationSettingsStates.fromIntent(data);
        switch (requestCode){
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode){
                    case Activity.RESULT_OK:
                        break;
                    case Activity.RESULT_CANCELED:
                        startActivity(new Intent(getApplicationContext(),Login_page.class));
                        break;
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
        Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_FINE_LOCATION:
                if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

                }
                else {

                }
                return;
        }
    }
}

Logcat :

FATAL EXCEPTION: main Process: com.bigfoot.trialapp, PID: 17660 java.lang.IllegalArgumentException: GoogleApiClient parameter is required. at com.google.android.gms.common.internal.zzaa.zzb(Unknown Source) at com.google.android.gms.location.LocationServices.zzj(Unknown Source) at com.google.android.gms.location.internal.zzd.getLastLocation(Unknown Source) at com.bigfoot.trialapp.GpsPlaceSearch.onConnected(GpsPlaceSearch.java:128) at com.google.android.gms.common.internal.zzk.zzp(Unknown Source) at com.google.android.gms.internal.zzrd.zzn(Unknown Source) at com.google.android.gms.internal.zzrb.zzass(Unknown Source) at com.google.android.gms.internal.zzrb.onConnected(Unknown Source) at com.google.android.gms.internal.zzrf.onConnected(Unknown Source) at com.google.android.gms.internal.zzqr.onConnected(Unknown Source) at com.google.android.gms.common.internal.zzj$1.onConnected(Unknown Source) at com.google.android.gms.common.internal.zze$zzj.zzavj(Unknown Source) at com.google.android.gms.common.internal.zze$zza.zzc(Unknown Source) at com.google.android.gms.common.internal.zze$zza.zzv(Unknown Source) at com.google.android.gms.common.internal.zze$zze.zzavl(Unknown Source) at com.google.android.gms.common.internal.zze$zzd.handleMessage(Unknown Source) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Vivek Mishra
  • 5,669
  • 9
  • 46
  • 84
  • 2
    So what happens with your current code? Are you able to reduce it to a rather more minimal example? (You've posted nearly 200 lines of code at the moment - I doubt that it's *all* completely required in order to show the problem.) – Jon Skeet Mar 29 '17 at 07:15
  • What is at line no 128 in your class? – Vivek Mishra Mar 29 '17 at 07:18
  • it is giving me null pointer exception that googleapiclient parameter is required but i have initialize the googleapiclient – Vishal rana Mar 29 '17 at 07:18
  • @VivekMishra line 128: location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient); – Vishal rana Mar 29 '17 at 07:19
  • From what you have posted it's illegal argument exception not null pointer – Vivek Mishra Mar 29 '17 at 07:19
  • @VivekMishra ohh yes my mistake it is illiegal argument exception – Vishal rana Mar 29 '17 at 07:20
  • @VivekMishra so can you please tell me what is the problem in my code and help me out – Vishal rana Mar 29 '17 at 07:21
  • http://stackoverflow.com/questions/35825061/java-lang-illegalargumentexception-googleapiclient-parameter-is-required check this link – Vivek Mishra Mar 29 '17 at 07:22
  • @VivekMishra as you can see my code that i had initialize the googleapiclient in my oncreate and but still it is giving me the exception. – Vishal rana Mar 29 '17 at 07:24
  • you have initialized it twice so first check which one you are using and debug your code and check whether it is initialised properly or not – Vivek Mishra Mar 29 '17 at 07:27

1 Answers1

1

You should remove below line from onConnected

 location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient);

and should only call requestLocationUpdates method in onConnected

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onConnected(Bundle bundle) {

    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},108);
        LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient,locationRequest1,this);

    } 
}else{
    //custom dialog for "please enable location permission to access device location"
}
Kishore Jethava
  • 6,666
  • 5
  • 35
  • 51