Will Nilges
Will Nilges

Reputation: 170

How to show alert dialogue from another thread?

I've got an app that has a class that's linked to a layout. This layout then runs a process in another thread to avoid freezing the layout. Eventually, the code in the second thread is supposed to show a dialogue on the layout in the first thread. The code is running. I know this because I put a print statement at the end of it, but the dialogue isn't showing up.

So how do I make the dialogue show up once the thread is done? As far as I can tell, I can't just plop it into another thread, so i'm stumped. Any help would be appreciated.

Upvotes: 0

Views: 2450

Answers (2)

Pritesh Patel
Pritesh Patel

Reputation: 698

Create object of Handler in onCreate()

 mHandler=new Handler();

then

write following code inside your thread where you want to display dialog or to update any UI views.

mHandler.post(new Runnable() {
    public void run(){

        AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
        //Add all dialog prepaation code
    }
});

For more information refer Background processing in Android

Upvotes: 1

Siva agarwal
Siva agarwal

Reputation: 107

You need to use runOnUiThread from the thread to access your views and update/edit it.

runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn.setText("#");
                        //show your dialog here
                       //do your work here
                    }
                });

and if you are using fragments just add getActivity() before runOnUiThread

Upvotes: 1

Related Questions