techno
techno

Reputation: 6500

Async Worker Crashes App

I have written the following code within the main class for an async worker

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

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

              Toast.makeText(getApplicationContext(), "works... ", Toast.LENGTH_LONG).show();
            return null;
        }





         protected void onProgressUpdate(Integer... progress) {

         }

         protected void onPostExecute(Long result) {

         }
     }

But calling this crashes the app

public void render(View v)
    {
        new Renderer().execute();
    }

Can some one tell me what's going wrong?

Upvotes: 0

Views: 116

Answers (5)

Meenaxi
Meenaxi

Reputation: 567

 runOnUiThread(new Runnable() {
                   @Override
                   public void run() { 
                    Toast.makeText(getApplicationContext(), "works... ", Toast.LENGTH_LONG).show();
                   }
                });`

Try to do all ui work on main thread.

Upvotes: 0

FD_
FD_

Reputation: 12919

An AsyncTask is a helper around Threads and Handlers. It helps you to perform a background task and update the UI regularly.

Thus, the methods of AsyncTask run on different Threads: doInBackground runs in a background Thread onProgressUpdate and onPostExecute run on the UI Thread.

Now, you can only modify the UI in the UI Thread (=main Thread). This is why your code leads to a crash. Simply moving your Toast into onPostExecute will solve your problem.

Upvotes: 0

Geralt_Encore
Geralt_Encore

Reputation: 3771

You can't access UI thread from background thread.

Upvotes: 0

Ken Wolf
Ken Wolf

Reputation: 23269

You can't do a Toast in doInBackground, you will get Can't create handler inside thread that has not called Looper.prepare().

If it's just for testing at this stage (which your code seems to imply), consider instead just writing some log output for now.

Alternatively put your Toast either onPreExecute or onPostExecute

More info: How to raise a toast in AsyncTask, I am prompted to used the Looper

Upvotes: 1

Raghunandan
Raghunandan

Reputation: 133560

You are showing toast in doInbackground which is not possible. Do it in onPostExecute

  protected void onPostExecute(Long result) {
            Toast.makeText(getApplicationContext(), "works... ", Toast.LENGTH_LONG).show();
     }

doInbackground is invoked on the background thread. You should update ui on the ui thread. You can alos display toast in onProgressUpdate.

More info at

http://developer.android.com/reference/android/os/AsyncTask.html

Check the topic under the section The 4 steps.

Upvotes: 0

Related Questions