Location returning null sometime after Location Service is turned on Android -


i trying latitude , longitude device using fusedlocationapi . if location turned off asking user turn on location service through dialog. once location service turned on sometime getting longitude , latitude . sometime returning location null. here code latitude , longitude using fusedlocationapi. problem comes when user has turn on location service using dialog

private void getlatlong() {         mgoogleapiclient = new googleapiclient.builder(this)                 // next 2 lines tell new client “this” current class handle connection stuff                 .addconnectioncallbacks(this)                 .addonconnectionfailedlistener(this)                 //fourth line adds locationservices api endpoint googleplayservices                 .addapi(locationservices.api)                 .build();     }      @override     protected void onpause() {         super.onpause();         overridependingtransition(0, 0);         //disconnect api onpause()         if (mgoogleapiclient.isconnected()) {             locationservices.fusedlocationapi.removelocationupdates(mgoogleapiclient, this);             mgoogleapiclient.disconnect();         }     }      @override     public void onresume() {         super.onresume();         //now lets connect api         mgoogleapiclient.connect();     }      @override     public void onconnected(@nullable bundle bundle) {         if (mgoogleapiclient.isconnected()) {             log.e("googleapiclient", "connected");             settingsrequest();         }     }      private void settingsrequest() {         mlocationrequest = locationrequest.create()                 .setpriority(locationrequest.priority_high_accuracy)                 .setinterval(10 * 1000)        // 10 seconds, in milliseconds                 .setfastestinterval(1000); // 1 second, in milliseconds         locationsettingsrequest.builder builder = new locationsettingsrequest.builder().addlocationrequest(mlocationrequest);         builder.setalwaysshow(true); //this key ingredient          pendingresult<locationsettingsresult> result = locationservices.settingsapi.checklocationsettings(mgoogleapiclient, builder.build());         result.setresultcallback(new resultcallback<locationsettingsresult>() {             @override             public void onresult(locationsettingsresult result) {                 final status status = result.getstatus();                 log.e("statuscode", status.getstatuscode() + "");                 switch (status.getstatuscode()) {                     case locationsettingsstatuscodes.success:                         log.e("googleafterlocation", mgoogleapiclient.isconnected() + "");                         if (mgoogleapiclient.isconnected()) {                              // check if device has os marshmellow or greater                             if (build.version.sdk_int > build.version_codes.lollipop_mr1) {                                 if (activitycompat.checkselfpermission(registrationactivity.this, android.manifest.permission.access_fine_location) != packagemanager.permission_granted && activitycompat.checkselfpermission(registrationactivity.this, android.manifest.permission.access_coarse_location) != packagemanager.permission_granted) {                                     activitycompat.requestpermissions(registrationactivity.this, new string[]{android.manifest.permission.access_fine_location}, access_fine_location_code);                                 } else {                                     // location                                     location location = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient);                                      log.e("location", location + "");                                     if (location == null) {                                         locationservices.fusedlocationapi.requestlocationupdates(mgoogleapiclient, mlocationrequest, registrationactivity.this);                                          alerter.create(registrationactivity.this)                                                 .settitle(r.string.warning)                                                 .setduration(2000)                                                 .setbackgroundcolor(r.color.dot_dark_screen1)                                                 .settext("please turn on location settings , start application")                                                 .show();                                      } else {                                         //if went fine lets latitude , longitude                                         currentlatitude = location.getlatitude();                                         currentlongitude = location.getlongitude();                                         if (currentlatitude != -0.0 && currentlongitude != -0.0) {                                             //get weather data                                             //getweatherdata(currentlatitude, currentlongitude);                                             log.e("permissiongranted", currentlatitude + " " + currentlongitude);                                         } else {                                             alerter.create(registrationactivity.this)                                                     .settitle(r.string.warning)                                                     .settext("please check internet connectivity")                                                     .setduration(1500)                                                     .setbackgroundcolor(r.color.dot_dark_screen1)                                                     .show();                                         }                                         // toast.maketext(this, currentlatitude + " works " + currentlongitude + "", toast.length_long).show();                                     }                                 }                             } else {                                 // location                                 location location = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient);                                  if (location == null) {                                     locationservices.fusedlocationapi.requestlocationupdates(mgoogleapiclient, mlocationrequest, registrationactivity.this);                                  } else {                                     //if went fine lets latitude , longitude                                     currentlatitude = location.getlatitude();                                     currentlongitude = location.getlongitude();                                     if (currentlatitude != -0.0 && currentlongitude != -0.0) {                                         //get weather data                                         //getweatherdata(currentlatitude, currentlongitude);                                         log.e("lollipop", currentlatitude + " " + currentlongitude);                                     } else {                                         alerter.create(registrationactivity.this)                                                 .settitle(r.string.warning)                                                 .settext("please check internet connectivity")                                                 .setduration(1500)                                                 .setbackgroundcolor(r.color.dot_dark_screen1)                                                 .show();                                      }                                     // toast.maketext(this, currentlatitude + " works " + currentlongitude + "", toast.length_long).show();                                 }                             }                          }                         break;                     case locationsettingsstatuscodes.resolution_required:                         // location settings not satisfied. fixed showing user                         // dialog.                         try {                             // show dialog calling startresolutionforresult(),                             // , check result in onactivityresult().                             status.startresolutionforresult(registrationactivity.this, request_resolve_error);                         } catch (intentsender.sendintentexception e) {                             // ignore error.                         }                         break;                     case locationsettingsstatuscodes.settings_change_unavailable:                         // location settings not satisfied. however, have no way fix                         // settings won't show dialog.                         break;                 }             }         });     }      // method called on devices having installed android version >= m (marshmellow)     // method show user options allow or deny location services @ runtime     @override     public void onrequestpermissionsresult(int requestcode, string permissions[], int[] grantresults) {         switch (requestcode) {             case 3310: {                  if (grantresults.length > 0) {                      (int = 0, len = permissions.length; < len; i++) {                          if (grantresults[i] == packagemanager.permission_denied) {                             // show user dialog why need location                         } else if (grantresults[i] == packagemanager.permission_granted) {                             // location                             getlatlong();                         } else {                             finish();                         }                     }                 }                 return;             }         }     }      @override     public void onactivityresult(int requestcode, int resultcode, intent data) {         log.e("requestcode", requestcode + "");         if (requestcode == request_resolve_error) {             mresolvingerror = false;             switch (resultcode) {                 case activity.result_ok:                     log.e("locationdialog", "turned on");                     // location method                     if (activitycompat.checkselfpermission(registrationactivity.this, manifest.permission.access_fine_location) != packagemanager.permission_granted && activitycompat.checkselfpermission(registrationactivity.this, manifest.permission.access_coarse_location) != packagemanager.permission_granted) {                         // todo: consider calling                         //    activitycompat#requestpermissions                         // here request missing permissions, , overriding                         //   public void onrequestpermissionsresult(int requestcode, string[] permissions,                         //                                          int[] grantresults)                         // handle case user grants permission. see documentation                         // activitycompat#requestpermissions more details.                         return;                     }                     location location = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient);                      if (location == null) {                         locationservices.fusedlocationapi.requestlocationupdates(mgoogleapiclient, mlocationrequest, registrationactivity.this);                      } else {                         //if went fine lets latitude , longitude                         currentlatitude = location.getlatitude();                         currentlongitude = location.getlongitude();                         if (currentlatitude != -0.0 && currentlongitude != -0.0) {                             //get weather data                             //getweatherdata(currentlatitude, currentlongitude);                         } else {                              alerter.create(registrationactivity.this)                                     .settitle(r.string.warning)                                     .settext("please check internet connectivity")                                     .setduration(1500)                                     .setbackgroundcolor(r.color.dot_dark_screen1)                                     .show();                          }                          //toast.maketext(getactivity(), currentlatitude + " works " + currentlongitude + "", toast.length_long).show();                     }                     break;                 case activity.result_canceled:                     finish();                     break;             }         }     }       @override     public void onconnectionsuspended(int i) {      }      @override     public void onconnectionfailed(@nonnull connectionresult connectionresult) {         /*              * google play services can resolve errors detects.              * if error has resolution, try sending intent              * start google play services activity can resolve              * error.              */         if (connectionresult.hasresolution()) {             try {                 mresolvingerror = true;                 // start activity tries resolve error                 connectionresult.startresolutionforresult(registrationactivity.this, connection_failure_resolution_request);                     /*                      * thrown if google play services canceled original                      * pendingintent                      */             } catch (intentsender.sendintentexception e) {                 // log error                 mgoogleapiclient.connect();             }         } else {                 /*                  * if no resolution available, display dialog                  * user error.                  */             showerrordialog(connectionresult.geterrorcode());             mresolvingerror = true;             log.e("error", "location services connection failed code " + connectionresult.geterrorcode());         }     }      /* creates dialog error message */     private void showerrordialog(int errorcode) {         // create fragment error dialog         errordialogfragment dialogfragment = new errordialogfragment();         // pass error should displayed         bundle args = new bundle();         args.putint(dialog_error, errorcode);         dialogfragment.setarguments(args);         dialogfragment.show(getsupportfragmentmanager(), "errordialog");     }      /* called errordialogfragment when dialog dismissed. */     public static void ondialogdismissed() {         mresolvingerror = false;     }       /* fragment display error dialog */     public static class errordialogfragment extends dialogfragment {         public errordialogfragment() {         }          @override         public dialog oncreatedialog(bundle savedinstancestate) {             // error code , retrieve appropriate dialog             int errorcode = this.getarguments().getint(dialog_error);             return googleapiavailability.getinstance().geterrordialog(                     this.getactivity(), errorcode, request_resolve_error);         }          @override         public void ondismiss(dialoginterface dialog) {             ondialogdismissed();         }     }      @override     public void onlocationchanged(location location) {         currentlatitude = location.getlatitude();         currentlongitude = location.getlongitude();     } 

this line returning null after location turned on:

location location = locationservices.fusedlocationapi.getlastlocation(mgoogleapiclient); 


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -