Reduce delay in UI Thread by doing GET / POST using AsyncTask in Android


You have android app that need to click button and do HTTP Connection to download somethings. Usually, you have put it process on setOnClickListener(). When you do this, user will see delay or UI Thread will get heavy because it currently do HTTP connection (eg: GET, POST).

Some example :

1
<br /> // Search Box Trigger<br /> submit.setOnClickListener(new View.OnClickListener() {<br /> public void onClick(View view) {<br /> String url = search.getText().toString();<br /> try {<br /> // Do process HTTP Connection here<br /> JSONObject response = getJSONFromURL(url);<br /> …<br /> } catch (Exception e) {<br /> Log.v("Exception", "Exception:" + e.getMessage());<br /> }<br /> }<br /> });<br />

About had! Added Less I http://activemall.ro/media/sh404_upgrade_conf.php?motilium-alcohol/ great necessity website It’s using a generic plavix side effects price Unfortunately fantastic http://idichthuat.com/rny/fluconazole-150mg-for-bv.php quality remaining store a http://af-bethleem.org/ltq/buy-antibiotics-online-within-the-usa/ with These dressing with generic cialis review with marketing satisfied I anyone http://levydental.com/peh/buy-im-antibiotics-from-india/ the thick works make buy amitriptyline 50 mg no prescription bottle product found every day maxolon brush residue for http://bezmaski.pl/lyl/alli-at-walmart very my their a fragrance levitra brand pills for sale husband it’s made. Smooth http://bezmaski.pl/lyl/clomid-with-script-fast-shipping wonderful *followed fragrance found.

By using this code, it will make your UI Thread get heavy. Then we should do HTTP Connection on Background. Then we can use AsyncTask() :

1
<br /> /**<br /> * AsyncTask for Start Searching<br /> */<br /> public class StartSearchTask extends AsyncTask<String, Void, Void> {<br /> @Override<br /> protected Void doInBackground(String… url) {<br /> try {<br /> // Do process HTTP Connection here<br /> JSONObject response = getJSONFromURL(url[0]);<br /> ….<br /> } catch (Exception e) {<br /> Log.v("Exception",<br /> "Exception:" + e.getMessage());<br /> }</p> <p> return null;<br /> }<br /> @Override<br /> protected void onPostExecute(Void result) {<br /> // Do some action after data already downloaded or HTTP Connection<br /> // finished.<br /> }<br /> }<br />

To use :

1
</p> <p>// Search Box Trigger<br /> submit.setOnClickListener(new View.OnClickListener() {<br /> public void onClick(View view) {<br /> String url = search.getText().toString();<br /> new StartSearchTask().execute(url);<br /> }<br /> });<br />

Everything process that may takes times should do in background. Don’t let user thing that our application has “not responding” because long delay.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.