Viciouss
Viciouss

Reputation: 283

Calling same dialog from different threads

I have an android application with different activities and they all pull data from a web source. This is done by implementing Runnable and creating a thread with the activity as object. The basic class looks like this:

public ActivityX extends Activity implements Runnable {

    @Override
    public onResume() {
        super.onResume();
        Thread someThread = new Thread(this);
        someThread.start();
    }

    @Override
    public run() {
        try {
            // pull web content
        }
        catch(TimeOutException e) {
            // >>> create dialog here <<<
            // go back to another activity
        }
    }
}

I tried to create a dialog helper class with a static method that returns the timeout dialog and then call show() like this:

HelperClass.getTimeOutDialog().show();

but the problem is, I can't call it from inside the run() method, as it's in a different thread. If I try to, I will get a runtime exception stating:

Can't create handler inside thread that has not called Looper.prepare()

I need to do this dialog for nearly a dozen of activities and I really want to get around using a Handler objects and sending a message to call the dialog every time. Isn't there an easier way to do this? I just can't think of any right now unfortunately.

My code would look something like this:

handler.handleEmptyMessage(1);

This is to call the handler. And the following would handle the message:

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == 1) {
            // show dialog here
        }
    }
};

Cheers

Upvotes: 0

Views: 426

Answers (2)

Lawrence Gimenez
Lawrence Gimenez

Reputation: 3235

@Override
    public run() {
        try {
            // pull web content
        }
        catch(TimeOutException e) {
             runOnUiThread(new Runnable(){
                 @Override
                 public void run() {
                    // >>> create dialog here <<<
                    // go back to another activity
                 }  
             }

        }
    }

Try the one above if you don't want to use Handler.

Upvotes: 1

Akhil
Akhil

Reputation: 14038

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == 1) {
            // show dialog here
        }
    }
};

Is this code a part of your activity and not in a thread? If it is a part of your non Ui thread, it would give you the error message. Make sure the handler instance is created in your UI thread because a handler contains an implicit reference to the thread they get created in.

Upvotes: 0

Related Questions