httpclient - Android HTTP GET doesn't work -
i know java unfortunately chosen basic4android android development. after working on year realized should move in native solution. question might silly need advice solve it.
my goal retrieve data request. i've tried tons of android http client tutorials on internet failed each tutorial. i'm going share 1 here can me fix. when i'm clicking on button, nothing happening without tons of error message in logcat window.
main class here quick review:
public class mainactivity extends activity implements onclicklistener { private button test; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); test = (button) findviewbyid(r.id.test); test.setonclicklistener(this); } @override public void onclick(view v) { if (v.getid() == r.id.test){ try { httpclient client = new defaulthttpclient(); string geturl = "http://www.google.com"; httpget = new httpget(geturl); httpresponse responseget = client.execute(get); httpentity resentityget = responseget.getentity(); if (resentityget != null) { // response string response = entityutils.tostring(resentityget); log.i("get response", response); } } catch (exception e) { e.printstacktrace(); } } } }
and whole project here: https://dl.dropboxusercontent.com/u/15625012/testhttp.zip
i'll appreciate sort of help/advice.
you doing network access in main ui thread (button click function). android not allow long operations such network access in main thread ui thread of app. need asynchronously in separate thread. can use built in async class purpose.
here sample code wrote
public class sample extends activity { private progressdialog progress_dialog; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_sample); progress_dialog = new progressdialog(this); } public void mybuttonclick(view view) { edittext usernameedittext = (edittext)findviewbyid(r.id.sample_username); string username = usernameedittext.gettext(); string url = "http://some_website?username=" + username; progress_dialog.setmessage("loading. please wait..."); progress_dialog.setcancelable(false); progress_dialog.show(); new sampleasynthread().execute(url); } private class sampleasynthreadextends asynctask <string, void, string> { protected string doinbackground(string... urls) { // make request here return "response"; } protected void onpostexecute(string result) { // show response on ui progress_dialog.dismiss(); } } protected void ondestroy() { progress_dialog.dismiss(); super.ondestroy(); } @override protected void onpause() { progress_dialog.dismiss(); super.onpause(); } }
Comments
Post a Comment