android - getLastLocation does not work on second time -
i'm using google play services user's last known connection.
@override public void onconnected(bundle connectionhint) {     final location lastlocation = locationservices.fusedlocationapi.getlastlocation(                 _googleapiclient); }   @override     protected void onresume() {         super.onresume();          connecttogoogleplay();        }  @override     protected void onpause() {         super.onpause();         if (_googleapiclient != null) {             _googleapiclient.disconnect();         }     }   works expected.
the problem occurs whenever i'm clicking on button , starting application again. app crashes because getlastlocation return null. formal documentation states - 
if location not available, should happen rarely, null returned.
fine, know sure location exists, retrieved second ago.
i did quick experiment , removed _googleapiclient.disconnect(); , works, somehow disconnect erases last location
why ? missing ?
a few things consider:
1) should connect googleapiclient in onstart() , disconnect in  onstop(): 
@override protected void onstart() {     super.onstart();     mgoogleapiclient.connect(); }  @override protected void onstop() {     mgoogleapiclient.disconnect();     super.onstop(); }   2) code should assume getlastlocation() may return null. null check.
3) use islocationavailable() when working getlastlocation().  if returns true, location returned getlastlocation() can assumed reasonably date.
Comments
Post a Comment