VansFannel
VansFannel

Reputation: 45921

Show a Dialog inside a thread that it isn't GUI thread

I'm developing an Android 3.1 and above application.

I have added a thread to make a REST request using Spring Framework. This is my code:

public class FormsListActivity extends ListActivity
{
    private List<Form> forms;
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      progressDialog = ProgressDialog.show(this, "Please Wait.", "Loading forms...");
      getUpdates.start();
    }

    private Thread getUpdates = new Thread ()
    {
        public void run() 
        {
            try
            {
                forms = FormSpringController.LoadAll();
                progressDialog.dismiss();
            }
            catch (Exception e)
            {
                e.printStackTrace();
                //display = e.getLocalizedMessage();
            }

            runOnUiThread(new Runnable()
            {
                public void run()
                {
                    setListAdapter(new FormAdapter(FormsListActivity.this, R.layout.form_list_item, forms));

                    ListView lv = getListView();
                    lv.setTextFilterEnabled(true);
                }
            });
        }
    };
}

I want to show a dialog inside catch block:

catch (Exception e)
{
    e.printStackTrace();
    //display = e.getLocalizedMessage();
}

I've thought to set display variable it there is an error, and then check it inside runOnUiThread(new Runnable(). If display has a value then show a dialog.

What do you think? Is there any better approach?

Upvotes: 0

Views: 3438

Answers (2)

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

runOnUiThread(new Runnable(){
public void run(){
////code for alert dialog
}
});

is not recommened but you can use it. Better to go with another thread that handled all UI tasks.

Upvotes: 0

Ravi1187342
Ravi1187342

Reputation: 1277

check out this . put all code of your thread's run method inside handleMessage(Message message) method

private Handler handler = new Handler(){
        public void handleMessage(Message message){
             try
             {
                 forms = FormSpringController.LoadAll();
                 progressDialog.dismiss();
                 setListAdapter(new FormAdapter(FormsListActivity.this, R.layout.form_list_item, forms));

                 ListView lv = getListView();
                 lv.setTextFilterEnabled(true);
             }
             catch (Exception e)
             {
                 e.printStackTrace();
                 //display = e.getLocalizedMessage();
             }

        }
    }

and call this inside your Thread's run method

handler .sendEmptyMessage(0);

Upvotes: 2

Related Questions