android - GoogleApiClient is not connected despite onconnect() being called? -


i want add geofence on current location of user when user clicks on ad geofence button.however,after using fused api client states not connected yet.here code-

import android.manifest; import android.app.service; import android.content.context; import android.content.pm.packagemanager; import android.database.sqlite.sqlitedatabase; import android.location.criteria; import android.location.location; import android.location.locationmanager; import android.os.build; import android.os.bundle; import android.support.v4.app.activitycompat; import android.support.v4.app.fragmentactivity; import android.util.log; import android.view.view; import android.widget.toast;  import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.api.googleapiclient; import com.google.android.gms.location.geofence; import com.google.android.gms.location.locationrequest; import com.google.android.gms.location.locationservices; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.cameraposition; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions;  import java.util.arraylist;  public class mapsactivity extends fragmentactivity implements com.google.android.gms.location.locationlistener, googleapiclient.connectioncallbacks, googleapiclient.onconnectionfailedlistener {      private googlemap googlemap; // might null if google play services apk not available.     public sqlitedatabase db;     arraylist<geofence> mgeofences;     public double latitude = 77.80;     public double longitude = 55.76;     double valueindex = 0.0;     private int request = 0;     private locationrequest mlocationrequest;     private googleapiclient mgoogleapiclient;     /**      * geofence coordinates      */     arraylist<latlng> mgeofencecoordinates;     /**      * geofence store      */     private geofencestore mgeofencestore;       @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         mgeofences = new arraylist<geofence>();         mgeofencecoordinates = new arraylist<latlng>();         db = openorcreatedatabase("coordsdb", context.mode_private, null); //        db.execsql("create table if not exists coordinates(number double,latitude double,longitude double);"); //        db.execsql("insert coordinates values('fixed', 28.61,77.20)");         setcontentview(r.layout.activity_maps);         supportmapfragment supportmapfragment =                 (supportmapfragment) getsupportfragmentmanager().findfragmentbyid(r.id.googlemap);         /**          * supportmapfragment belongs v4 support library, contrary default magfragment native component in android.          supportmapfragment support more android versions, additional library have add in project,          think depends on android versions targeting:          •  on recent versions, default components should enough          •  on older versions need install v4 support library , maybe others          *          */         googlemap = supportmapfragment.getmap();         log.i("my activity", "maps=" + googlemap);         googlemap.setmylocationenabled(true);         /**          * setmylocationenabled(true/false) shows true location when gps switched on device. inbuilt feature of googlemaps .          */          locationmanager locationmanager = (locationmanager) getsystemservice(service.location_service);         // getting gps status         boolean isgpsenabled = locationmanager.isproviderenabled(locationmanager.gps_provider);         log.i("my activity", "gps is" + isgpsenabled);          // getting network status         boolean isnetworkenabled = locationmanager                 .isproviderenabled(locationmanager.network_provider);         log.i("my activity", "network is" + isnetworkenabled);          criteria crta = new criteria();         if (build.version.sdk_int > build.version_codes.gingerbread) {             crta.setaccuracy(criteria.accuracy_fine);         } else {             crta.setaccuracy(criteria.accuracy_medium);         }         /**          * have used .setaccuracy fine higher sdks gingerbread .gingerbread used reference because in apks lower          * gingerbread there poor geofencing, gingerbread google made lot easier locationservices used devleopers.          * had improved set of tools location services, included geofencing , substantially improved location discovery.          */         crta.setpowerrequirement(criteria.power_low);         string provider = locationmanager.getbestprovider(crta, true);          /**          * request location updates after every 5 sec or if user traveled 10m          */         log.i("my activity", "manager " + locationmanager);         log.i("my activity", "provider " + provider);         if (build.version.sdk_int >= build.version_codes.m) {             if (activitycompat.checkselfpermission(this, manifest.permission.access_fine_location) != packagemanager.permission_granted && activitycompat.checkselfpermission(this, manifest.permission.access_coarse_location) != packagemanager.permission_granted) {                  mapsactivity.this.requestpermissions(new string[]{manifest.permission.access_fine_location}, 100);                 // here request missing permissions, , overriding                 //   public void onrequestpermissionsresult(int requestcode, string[] permissions,                 //                                          int[] grantresults)                 // handle case user grants permission. see documentation                 // activity#requestpermissions more details.                 return;             }         }         if (mgoogleapiclient == null) {             mgoogleapiclient = new googleapiclient.builder(this)                     .addconnectioncallbacks((googleapiclient.connectioncallbacks) this)                     .addonconnectionfailedlistener((googleapiclient.onconnectionfailedlistener) this)                     .addapi(locationservices.api)                     .build();             mgoogleapiclient.connect();             log.i("api is",""+mgoogleapiclient);         }         mlocationrequest = new locationrequest();         // want location update every 10 seconds.         mlocationrequest.setinterval(10000);         // want location accurate possible.         mlocationrequest.setpriority(locationrequest.priority_high_accuracy);  //        location location = locationmanager.getlastknownlocation(provider);         location location = locationservices.fusedlocationapi.getlastlocation(                 mgoogleapiclient);         startlocationupdates();         log.i("location is", location + "");            if (location != null) {              onlocationchanged(location);         }           /**          * permission requested after every  sec or @ distance of 0 metres user.          */       }      @override     public void onrequestpermissionsresult(int requestcode, string[] permissions, int[] grantresults) {         switch (requestcode) {             case 100: {                 if (grantresults[0] == packagemanager.permission_granted) {                     toast.maketext(this, "thanks permission", toast.length_long).show();                     // permission granted, yay!                     // calendar task need do.                 } else {                     // permission denied, boo! disable                     // functionality depends on permission.                     toast.maketext(this, "you did not allow access current location", toast.length_long).show();                 }             }             // other 'switch' lines check other             // permissions app might request         }     }       @override     public void onlocationchanged(location location) {         cameraposition init =                 new cameraposition.builder()                         .target(new latlng(location.getlatitude(), location.getlongitude()))                         .zoom(17.5f)                         .bearing(300f) // orientation                         .tilt(50f) // viewing angle                         .build();         // use googglemap mmap move camera position         googlemap.animatecamera(cameraupdatefactory.newcameraposition(init));     }      @override     protected void onstart() {          super.onstart();         mgoogleapiclient.connect();     }      @override     protected void onstop() {          super.onstop();         mgoogleapiclient.disconnect();      }       public void add(view view) {         if (request <= 3) {             mgeofencecoordinates.add(new latlng(latitude, longitude));             log.i("the id is", "" + valueindex);             mgeofences.add(new geofence.builder()                     // coordinates of center of geofence , radius in meters.                     .setrequestid("" + valueindex)                     .setcircularregion(latitude, longitude, 30)                     .setexpirationduration(geofence.never_expire)                             // required when use transition type of geofence_transition_dwell                     .setloiteringdelay(50000)                     .settransitiontypes(                             geofence.geofence_transition_enter                                     | geofence.geofence_transition_dwell                                     | geofence.geofence_transition_exit).build());             mgeofencestore = new geofencestore(this, mgeofences);             valueindex++;             request++;  //            cursor c = db.rawquery("select * coordinates id='"+valueindex+"'", null);               googlemap.addmarker(new markeroptions().snippet("radius:30m").draggable(false).title(valueindex + "").position(new latlng(latitude, longitude)));         } else {             toast.maketext(this, "maximum limit exceeded", toast.length_long).show();         }     }      @override     public void onconnected(bundle bundle) {         location mlastlocation;         if (build.version.sdk_int >= build.version_codes.m) {             if (checkselfpermission(manifest.permission.access_fine_location) != packagemanager.permission_granted && checkselfpermission(manifest.permission.access_coarse_location) != packagemanager.permission_granted) {                  mapsactivity.this.requestpermissions(new string[]{manifest.permission.access_fine_location}, 100);                 //    public void requestpermissions(@nonnull string[] permissions, int requestcode)                 // here request missing permissions, , overriding                 //   public void onrequestpermissionsresult(int requestcode, string[] permissions,                 //                                          int[] grantresults)                 // handle case user grants permission. see documentation                 // activity#requestpermissions more details.                 return;             }         }             mlastlocation = locationservices.fusedlocationapi.getlastlocation(                     mgoogleapiclient);            startlocationupdates();             if (mlastlocation != null) {                 log.i("the last location:", "" + mlastlocation);                 toast.maketext(this, "get last location first asshole!", toast.length_long).show();             }           }       protected void startlocationupdates() {         if (build.version.sdk_int >= build.version_codes.m) {             if (checkselfpermission(manifest.permission.access_fine_location) != packagemanager.permission_granted && checkselfpermission(manifest.permission.access_coarse_location) != packagemanager.permission_granted) {                 mapsactivity.this.requestpermissions(new string[]{manifest.permission.access_fine_location}, 100);                 //    public void requestpermissions(@nonnull string[] permissions, int requestcode)                 // here request missing permissions, , overriding                 //   public void onrequestpermissionsresult(int requestcode, string[] permissions,                 //                                          int[] grantresults)                 // handle case user grants permission. see documentation                 // activity#requestpermissions more details.                 return;             }             locationrequest mlocationrequest = new locationrequest();              locationservices.fusedlocationapi.requestlocationupdates(                     mgoogleapiclient, mlocationrequest, this);         }     }      @override     public void onconnectionsuspended(int i) {         log.i("connection","suspended");     }      @override     public void onconnectionfailed(connectionresult connectionresult) {     log.i("connection","failed");     } } 

here error-

java.lang.runtimeexception: unable start activity componentinfo{saksham.geofencing/saksham.geofencing.mapsactivity}: java.lang.illegalstateexception: googleapiclient not connected yet.             @ android.app.activitythread.performlaunchactivity(activitythread.java:2426)             @ android.app.activitythread.handlelaunchactivity(activitythread.java:2490)             @ android.app.activitythread.-wrap11(activitythread.java)             @ android.app.activitythread$h.handlemessage(activitythread.java:1354)             @ android.os.handler.dispatchmessage(handler.java:102)             @ android.os.looper.loop(looper.java:148)             @ android.app.activitythread.main(activitythread.java:5443)             @ java.lang.reflect.method.invoke(native method)             @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:728)             @ com.android.internal.os.zygoteinit.main(zygoteinit.java:618)      caused by: java.lang.illegalstateexception: googleapiclient not connected yet.             @ com.google.android.gms.common.api.internal.zzh.zzb(unknown source)             @ com.google.android.gms.common.api.internal.zzl.zzb(unknown source)             @ com.google.android.gms.common.api.internal.zzj.zzb(unknown source)             @ com.google.android.gms.location.internal.zzd.requestlocationupdates(unknown source)             @ saksham.geofencing.mapsactivity.startlocationupdates(mapsactivity.java:276)             @ saksham.geofencing.mapsactivity.oncreate(mapsactivity.java:139)             @ android.app.activity.performcreate(activity.java:6245)             @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1130)             @ android.app.activitythread.performlaunchactivity(activitythread.java:2379)             at android.app.activitythread.handlelaunchactivity(activitythread.java:2490)             at android.app.activitythread.-wrap11(activitythread.java)             at android.app.activitythread$h.handlemessage(activitythread.java:1354)             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) 

and manifest file-

<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="saksham.geofencing" >      <uses-permission android:name="android.permission.internet" />     <uses-permission android:name="android.permission.access_network_state" />     <uses-permission android:name="android.permission.write_external_storage" />      <uses-permission android:name="com.google.android.providers.gsf.permission.read_gservices" />     <!--  access_coarse/fine_location permissions not required use          google maps android api v2, recommended.     -->     <uses-permission android:name="android.permission.access_coarse_location" />     <uses-permission android:name="android.permission.access_fine_location" />      <application         android:allowbackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:theme="@style/apptheme" >         <meta-data             android:name="com.google.android.gms.version"             android:value="@integer/google_play_services_version" />         <meta-data             android:name="com.google.android.maps.v2.api_key"             android:value="@string/google_maps_key" />          <activity             android:name=".mapsactivity"             android:label="@string/title_activity_maps" >             <intent-filter>                 <action android:name="android.intent.action.main" />                  <category android:name="android.intent.category.launcher" />             </intent-filter>         </activity>      </application>     <receiver android:name="com.aol.android.geofence.geofencereceiver"         android:exported="false">         <intent-filter >             <action android:name="com.aol.android.geofence.action_receive_geofence"/>         </intent-filter>     </receiver>  </manifest> 

please help,i newbie android , have been stuck @ many days after searching countless blogs

in oncreate method, correctly configure google api client , call onconnect:

if (mgoogleapiclient == null) {     mgoogleapiclient = new googleapiclient.builder(this)             .addconnectioncallbacks((googleapiclient.connectioncallbacks) this)             .addonconnectionfailedlistener((googleapiclient.onconnectionfailedlistener) this)             .addapi(locationservices.api)             .build();     mgoogleapiclient.connect();     log.i("api is",""+mgoogleapiclient); } 

however, several lines below (still within oncreate lifecycle method), have following code:

location location = locationservices.fusedlocationapi.getlastlocation(             mgoogleapiclient); startlocationupdates(); log.i("location is", location + "");  if (location != null) {     onlocationchanged(location); } 

my guess first line of section causing error - trying retrieve location google api client still not connected @ point. since have analogous code inside onconnected callback, should able remove second block of code quoted above oncreate method fix issue.


Comments