Caution Continues
Caution Continues

Reputation: 753

Timer and Async Together

I want to trigger AsynTask inside the Timer thread, I am getting this following error.

java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Is it possible or not ??? Here is my code

networkTimer = new Timer();
                networkTimer.schedule(new TimerTask() {
                    int counter = 1;
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if(isNetworkAvailable()){
                            Log.d("Hey I got the Network","!!");
                            new GmailAsync().execute("");
                            networkTimer.cancel();
                        }else{
                            Log.d("Attempt","No:"+counter);
                            counter++;
                            if(counter == 6){
                                Log.d("Attempt","Finished");
                                networkTimer.cancel();
                            }
                        }
                    }
                },0, 5000);

Upvotes: 0

Views: 134

Answers (1)

njzk2
njzk2

Reputation: 39386

AsyncTask.execute() must be run on the UI Thread, which your TimerTask does not.

Suggestions : * Use runOnUiThread to go back to UI Thread to use your AsyncTask * Don't use a timer, but rather a handler and postDelyaed * Don't use an AsyncTask if you don't need to interact with the UI (which you may, but i don't know what your AsyncTask does.

Best solution is #2. That would look like :

mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        if(isNetworkAvailable()){
            Log.d("Hey I got the Network","!!");
            new GmailAsync().execute("");
        }else{
            Log.d("Attempt","No:"+counter);
            counter++;
            if(counter == 6){
                Log.d("Attempt","Finished");
            } else {
                mHandler.postDelayed(this, 5000);
            }
        }
    }, 5000);
}

as long as counter < 6, the runnable repost itself

Upvotes: 1

Related Questions