location - how to get lat and long in android -
i facing minor problem in code , getting stuck due it.following code:-
public class mainactivity extends activity { textview textview1; location currentlocation; double currentlatitude,currentlongitude; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); textview1 = (textview) findviewbyid(r.id.textview1); findlocation(); textview1.settext(string.valueof(currentlatitude) + "\n" + string.valueof(currentlongitude)); } public void findlocation() { locationmanager locationmanager = (locationmanager) .getsystemservice(context.location_service); locationlistener locationlistener = new locationlistener() { public void onlocationchanged(location location) { updatelocation(location,currentlatitude,currentlongitude); toast.maketext( mainactivity.this, string.valueof(currentlatitude) + "\n" + string.valueof(currentlongitude), 5000) .show(); } public void onstatuschanged(string provider, int status, bundle extras) { } public void onproviderenabled(string provider) { } public void onproviderdisabled(string provider) { } }; locationmanager.requestlocationupdates( locationmanager.network_provider, 0, 0, locationlistener); } void updatelocation(location location,double currentlatitude,double currentlongitude) { currentlocation = location; this.currentlatitude = currentlocation.getlatitude(); this.currentlongitude = currentlocation.getlongitude(); } }
every thing working fine.but problem class level variables currentlatitude , currentlongitude having values null.in above code when setting lat , long in text view in update location method,it works fine when want set same values in text view in on create method gives null value.why dont know.please sort out problem.thanks in advance!
its because when set text in textview in oncreate method lat , long not initialized. initialized when gets updated.
so should settext in updatelocation() method.
locationlistener take sometime update lat , long oncreate method executed meanwhile lat , long not updated , stays null. better settext on updatelocation.
hope helps!!
Comments
Post a Comment