user2130898
user2130898

Reputation: 899

Using AsyncTask

I am newbie in android and I was trying to fetch some data from a server and print it in my device. I realize that with android 4.x we are not able to do that because the UI thread get blocked. I make my research and found AsyncTask. Can someone give me a little help with my code? Is there something missing? Thanks

Here is my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new Thread().execute();        
    openDialog(getCurrentFocus());

}

AsynTask Class:

    private class Thread extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

               //Here i make a HTTP request.

         return null;
    }
   } 

LogCat:

04-22 22:43:10.808: E/Trace(12987): error opening trace file: No such file or directory (2)
04-22 22:43:11.098: E/AndroidRuntime(12987): FATAL EXCEPTION: AsyncTask #1

04-22 22:43:11.098: E/AndroidRuntime(12987): java.lang.RuntimeException: An error occured while executing doInBackground()
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.lang.Thread.run(Thread.java:856)
04-22 22:43:11.098: E/AndroidRuntime(12987): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.os.Handler.<init>(Handler.java:197)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.os.Handler.<init>(Handler.java:111)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.widget.Toast$TN.<init>(Toast.java:324)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.widget.Toast.<init>(Toast.java:91)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.widget.Toast.makeText(Toast.java:238)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at com.application.uprm_map.MainActivity.startApplication(MainActivity.java:72)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at com.application.uprm_map.MainActivity.access$0(MainActivity.java:67)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at com.application.uprm_map.MainActivity$Thread.doInBackground(MainActivity.java:439)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at com.application.uprm_map.MainActivity$Thread.doInBackground(MainActivity.java:1)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-22 22:43:11.098: E/AndroidRuntime(12987):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-22 22:43:11.098: E/AndroidRuntime(12987):    ... 3 more
04-22 22:43:11.413: E/WindowManager(12987): Activity com.application.uprm_map.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{421b4b58 V.E..... R.....I. 0,0-720,412} that was originally added here
04-22 22:43:11.413: E/WindowManager(12987): android.view.WindowLeaked: Activity com.application.uprm_map.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{421b4b58 V.E..... R.....I. 0,0-720,412} that was originally added here
04-22 22:43:11.413: E/WindowManager(12987):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
04-22 22:43:11.413: E/WindowManager(12987):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)

Upvotes: 0

Views: 3296

Answers (1)

kaderud
kaderud

Reputation: 5497

I've attached an example to post parameters to a webpage using AsyncTask (simplified, it should handle isCancelled for one) It shouldn't be too hard for you to adapt it your needs.

AsyncTask usage

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)

AsyncTask's generic types

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.

Progress, the type of the progress units published during the background computation.

Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Read more on AsyncTask (above documentation taken from the following link) at http://developer.android.com/reference/android/os/AsyncTask.html

An example to POST to a web page

// (declaration in main class)
private MyNetworkTask mMyNetworkTask = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String mURL = "http://www.mydomain.com/mycode.php";
    runMyTask(this, mURL);
}

private class MyNetworkTask extends AsyncTask<String, Void, HttpResponse> { // <doInBackground, onProgressUpdate, onPostExecute>

    private ProgressDialog dialog;
    private Context context;

    public MyNetworkTask(Context ctx) {
        context = ctx;
        dialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Working ...");
        dialog.show();
    }
    @Override
    protected HttpResponse doInBackground(final String... params) {
        String mURL = params[0];
        HttpParams httpparams = new BasicHttpParams();
        HttpProtocolParams.setContentCharset(httpparams, "UTF-8");

        HttpClient httpclient = new DefaultHttpClient(httpparams);
        HttpPost httppost = new HttpPost(mURL);
        httppost.setHeader("User-Agent", "MyUserAgent/1.0");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
        nameValuePairs.add(new BasicNameValuePair("param2", "value2"));
        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            return httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    protected void onPostExecute(final HttpResponse result) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (result != null) {
            int responseCode = result.getStatusLine().getStatusCode();
            String responseBody="";
            switch(responseCode) {
            case 200:
                HttpEntity entity = result.getEntity();
                if(entity != null) {
                    try {
                        responseBody = EntityUtils.toString(entity);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
            Log.v(TAG, "Response Code => " + responseCode);
            Log.i(TAG, "Response Body => " + responseBody);
        }
    }

    @Override
    protected void onCancelled() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
} // AsyncTask

private void runMyTask(Context ctx, String url) {
    if (mMyNetworkTask != null) {
            return;
        }
        mMyNetworkTask = new NetworkTask(this);
        mMyNetworkTask .execute(url);
}

Upvotes: 5

Related Questions