Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: why i get these AsyncTask Error?

i have an asyncTaskProc that read some info from a DB and write it on the ui...

the code works perfectcly on Android 4.0 but doesn't work on 2.3... here is the code

NEW ASYNCTASK

`public class IceCastPoll extends TimerTask {

    public IceCastPoll() {

    }

    @TargetApi(9)
    public void run() {

        new AsyncTaskProc().execute();   
    }

}`

THE ASYNCTASK implementation

@TargetApi(9)
class AsyncTaskProc extends AsyncTask<Void, String, Void> {
    List<Stream> streams=null;

    @Override
    protected void onPostExecute(Void result) {

        textSong =(TextView) findViewById(R.id.textViewCurrentSong);
        textArtist =(TextView) findViewById(R.id.textViewCurrentArtist);
        textTit=(TextView) findViewById(R.id.textViewTit);
        textArt=(TextView) findViewById(R.id.TextViewArt);
        copertina=(ImageView) findViewById(R.id.imageViewCopertina);
        new DownloadImageTask((ImageView) findViewById(R.id.imageViewCopertina)).execute("http://service.uniradiocesena.it/OnAir.jpg");

        try {
            for (Stream stream: streams) {

                try
                {   
                    //Thread.sleep(5000);
                    //textSong.setText((stream.getCurrentSong()));
                    textArt.setText("Artista:");
                    textTit.setText("Titolo:");
                    StringTokenizer tokens = new StringTokenizer(stream.getCurrentSong(), "-");
                    String first = tokens.nextToken();
                    String second = tokens.nextToken();
                    textSong.setText(first);
                    textArtist.setText(second);

                } catch (Exception e) { 
                    //Thread.sleep(5000);
                    textSong.setText((stream.getCurrentSong()));
                    textArt.setText("Rotazione:");
                    textTit.setText("");
                    textArtist.setText("");
                }
            }
        } catch (Exception e) {

            //Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show();

        }

    }

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



        Scraper scraper = new IceCastScraper();

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);


        try {
            streams = scraper.scrape(new URI("http://r35798.ovh.net:8000/"));

        } catch (ScrapeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
        }




        return (null);
    }


}`

THE LOGCAT ERRORS

11-07 11:09:49.729: W/dalvikvm(18983): Exception Ljava/lang/RuntimeException; thrown while initializing Landroid/os/AsyncTask;
11-07 11:09:49.729: W/dalvikvm(18983): threadid=9: thread exiting with uncaught exception (group=0x40018560)
11-07 11:09:49.739: E/AndroidRuntime(18983): FATAL EXCEPTION: Timer-0
11-07 11:09:49.739: E/AndroidRuntime(18983): java.lang.ExceptionInInitializerError
11-07 11:09:49.739: E/AndroidRuntime(18983):    at com.example.appuniradiocesena.SwipeyTabsSampleActivity$IceCastPoll.run(SwipeyTabsSampleActivity.java:233)
11-07 11:09:49.739: E/AndroidRuntime(18983):    at     java.util.Timer$TimerImpl.run(Timer.java:284)
11-07 11:09:49.739: E/AndroidRuntime(18983): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-07 11:09:49.739: E/AndroidRuntime(18983):    at android.os.Handler.<init>(Handler.java:121)
11-07 11:09:49.739: E/AndroidRuntime(18983):    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
11-07 11:09:49.739: E/AndroidRuntime(18983):    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
11-07 11:09:49.739: E/AndroidRuntime(18983):    at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
11-07 11:09:49.739: E/AndroidRuntime(18983):    ... 2 more

Any suggestion it will be very very apreciated !

and sry for english mistakes :D

like image 408
radudac Avatar asked Nov 07 '12 10:11

radudac


People also ask

What is the problem with AsyncTask in Android?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

What is meant by AsyncTask in Android?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

What replaces AsyncTask Android?

3. AsyncTask deprecated alternative Android – Kotlin. Here, we are using the Executor class as an alternative to the deprecated AsyncTask. A Handler gives you a mechanism to push tasks into the UI thread queue from any other threads thus allowing other threads to communicate with the UI thread.

How do I know if AsyncTask is running on Android?

Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.


2 Answers

You should start AsyncTask with a Handler created on main thread. So replace your run() method in IceCastPoll with this one:

private Handler handler = new Handler(Looper.getMainLooper());

@Override
public void run() {
   handler.post(new Runnable() {
      public void run() {
          new AsyncTaskProc().execute();
      }
   });
 }
like image 195
amukhachov Avatar answered Sep 28 '22 11:09

amukhachov


 new AsyncTaskProc().execute();    

Dont put this code inside a thread .

Because it is already a Handler.

Simple Execute the code where ever you need like new AsyncTaskProc().execute(); its enough my Friend

like image 38
Venkatesh S Avatar answered Sep 28 '22 12:09

Venkatesh S