timer - getting "java.lang.RuntimeException" when sending latitude and longitude to remote mysql database within service in android" -
i've created android application there 2 buttons start stop. when start button clicked on every 1 seconds current latitude , longitude values send usl post insert remote mysl database.
within start button wrote service myservice sending latitude , longitude.
within onstartcommand(..) method of myservice have wrote timer sending latitude , longitude @ 1 second.
but i'm getting following exception
java.lang.runtimeexception: can't create handler inside thread has not called looper.prepare()
can please tell me solution this
my code given below
iloadpage.java
import android.app.activity; import android.content.intent; import android.os.bundle; import android.view.view; import android.widget.button; public class iloadpage extends activity { button start,stop; boolean flag=true; double latin,longin,longitude,latitude; activity activity; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.iloadpage); start = (button) findviewbyid(r.id.startapp); stop = (button) findviewbyid(r.id.stop); stop.setenabled(false); start.setonclicklistener(new view.onclicklistener() { public void onclick(view arg0) { start.setenabled(false); stop.setenabled(true); string trackid= getintent().getextras().getstring("trackid"); myservice.settrackid(trackid); startservice(new intent(getbasecontext(),myservice.class)); } }); stop.setonclicklistener(new view.onclicklistener() { public void onclick(view arg0) { start.setenabled(true); stop.setenabled(false); stopservice(new intent(getbasecontext(),myservice.class)); } }); } @override public void ondestroy() { super.ondestroy(); } public double getlatin() { return latin; } public void setlatin(double latin) { this.latin = latin; } public double getlongin() { return longin; } public void setlongin(double longin) { this.longin = longin; } public double getlongitude() { return longitude; } public void setlongitude(double longitude) { this.longitude = longitude; } public double getlatitude() { return latitude; } public void setlatitude(double latitude) { this.latitude = latitude; } }
myservice .java
import java.util.arraylist; import java.util.list; import java.util.timer; import java.util.timertask; import java.util.concurrent.scheduledexecutorservice; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.message.basicnamevaluepair; import org.apache.http.util.entityutils; import android.app.service; import android.content.intent; import android.os.asynctask; import android.os.handler; import android.os.ibinder; import android.text.html; import android.widget.toast; public class myservice extends service { public static string trackid; scheduledexecutorservice scheduler ; gpstracker gps; boolean flag=false; downloadfile ss; handler handler = new handler(); double latin,longin,longitude,latitude; private final int ten_seconds = 3000; @override public ibinder onbind(intent arg0) { return null; } string errors="notnull"; @override public int onstartcommand(intent intent, int flags, int startid) { try { toast.maketext(this, "application service started!!!...", toast.length_long).show(); try { timertask mytimertask = new timertask() { @override public void run() { flag=true; downloadfile sd=new downloadfile(); sd.execute(""); } }; timer timer = new timer(); timer.schedule(mytimertask, 1000); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } }catch(exception e){ e.printstacktrace(); toast.maketext(this, "service error->"+e, toast.length_long).show();} return start_sticky; } @override public void ondestroy() { flag=false; super.ondestroy(); toast.maketext(this, "application service stopped!!!...", toast.length_long).show(); } public double getlatin() { return latin; } public void setlatin(double latin) { this.latin = latin; } public double getlongin() { return longin; } public void setlongin(double longin) { this.longin = longin; } public static string gettrackid() { return trackid; } public static void settrackid(string trackid) { copyofmyservice.trackid = trackid; } string pass; private class downloadfile extends asynctask<string, integer, string> { @override protected string doinbackground(string... surl) { try { gps = new gpstracker(copyofmyservice.this); latin = gps.getlatitude(); longin = gps.getlongitude(); httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("http://iloadlogistics.com.au/insert1.jsp"); string trackid= copyofmyservice.gettrackid(); list<namevaluepair> namevaluepairs = new arraylist<namevaluepair>(2); namevaluepairs.add(new basicnamevaluepair("trackid",trackid)); namevaluepairs.add(new basicnamevaluepair("lat",""+latin)); namevaluepairs.add(new basicnamevaluepair("lon",""+longin)); httppost.setentity(new urlencodedformentity(namevaluepairs)); httpresponse response = httpclient.execute(httppost); httpentity rp = response.getentity(); string origresponsetext = entityutils.tostring(rp); string htmltextstr = html.fromhtml(origresponsetext).tostring(); pass=htmltextstr.trim(); if(htmltextstr.trim().equals("success")) { }else if(htmltextstr.trim().equals("failure")){ } } catch (exception e) { pass=""+e; // todo auto-generated catch block system.out.println("errrrrrrrrrrrrrrrrror:"+e); e.printstacktrace(); } return pass; } @override protected void onpreexecute() { super.onpreexecute(); } @override protected void onpostexecute(string result) { super.onpostexecute(result); if(flag) { toast.maketext(getapplicationcontext(), "inserted!!!...", toast.length_short).show(); } else { toast.maketext(getapplicationcontext(), "asyntask destroying!!!...", toast.length_long).show(); ondestroy(); } } @override protected void onprogressupdate(integer... progress) { super.onprogressupdate(progress); } } }
gpstracker.java
public class gpstracker extends service implements locationlistener { private final context mcontext; boolean isgpsenabled = false; boolean isnetworkenabled = false; boolean cangetlocation = false; location location; // location double latitude; // latitude double longitude; // longitude private static final long min_distance_change_for_updates = 5; // 10 meters private static final long min_time_bw_updates = 1000; // 1 minute protected locationmanager locationmanager; public gpstracker(context context) { this.mcontext = context; getlocation(); } public location getlocation() { try { locationmanager = (locationmanager) mcontext .getsystemservice(location_service); // getting gps status isgpsenabled = locationmanager .isproviderenabled(locationmanager.gps_provider); // getting network status isnetworkenabled = locationmanager .isproviderenabled(locationmanager.network_provider); if (!isgpsenabled && !isnetworkenabled) { // no network provider enabled } else { this.cangetlocation = true; if (isnetworkenabled) { locationmanager.requestlocationupdates( locationmanager.network_provider, min_time_bw_updates, min_distance_change_for_updates, this); log.d("network", "network"); if (locationmanager != null) { location = locationmanager .getlastknownlocation(locationmanager.network_provider); if (location != null) { latitude = location.getlatitude(); longitude = location.getlongitude(); } } } // if gps enabled lat/long using gps services if (isgpsenabled) { if (location == null) { locationmanager.requestlocationupdates( locationmanager.gps_provider, min_time_bw_updates, min_distance_change_for_updates, this); log.d("gps enabled", "gps enabled"); if (locationmanager != null) { location = locationmanager .getlastknownlocation(locationmanager.gps_provider); if (location != null) { latitude = location.getlatitude(); longitude = location.getlongitude(); } } } } } } catch (exception e) { e.printstacktrace(); } return location; } public void stopusinggps(){ if(locationmanager != null){ locationmanager.removeupdates(gpstracker.this); } } public double getlatitude(){ if(location != null){ latitude = location.getlatitude(); } return latitude; } public double getlongitude(){ if(location != null){ longitude = location.getlongitude(); } return longitude; } public boolean cangetlocation() { return this.cangetlocation; } public void showsettingsalert(){ alertdialog.builder alertdialog = new alertdialog.builder(mcontext); alertdialog.settitle("gps settings"); alertdialog.setmessage("gps not enabled. want go settings menu?"); alertdialog.setpositivebutton("settings", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog,int which) { intent intent = new intent(settings.action_location_source_settings); mcontext.startactivity(intent); } }); // on pressing cancel button alertdialog.setnegativebutton("cancel", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int which) { dialog.cancel(); } }); // showing alert message alertdialog.show(); } public void onlocationchanged(location location) { } public void onproviderdisabled(string provider) { } public void onproviderenabled(string provider) { } public void onstatuschanged(string provider, int status, bundle extras) { } public ibinder onbind(intent arg0) { return null; } } updation 2
instead of timer used call method schedulesendlocation() has following definition given below
runnable r=new runnable() { public void run() { flag=true; downloadfile sd=new downloadfile(); sd.execute(""); handler.postdelayed(this, ten_seconds); } }; public void schedulesendlocation() { handler.postdelayed(r, ten_seconds); }
i don't see need handler for, see @ least 2 problems:
- you call
new handler()
in ui thread has no prepared looper - you create handler without overriding
handlemessage()
(what handler then?)
when create new handler
constructor has no parameter, handler associated message queue of current thread (calling new handler()
). means thread needs looper. can calling looper.prepare()
before creating handler.
however, can't yet because new handler()
called field initialization. should move call somewhere else, such in oncreate()
, add looper.prepare()
before it.
Comments
Post a Comment