I want to show this dialog, while the thread tries to build up a connection, but the dialog will not show up when I press the button which starts this method.
public void add_mpd(View view) {
dialog = ProgressDialog.show(MainActivity.this, "", "Trying to connect...");
new Thread(new Runnable() {
public void run() {
try {
String child;
EditText new_mpd = (EditText) findViewById(R.id.new_mpd);
child = new_mpd.getText().toString();
mpd = new MPD(child);
children.get(1).add(child);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MPDConnectionException e) {
e.printStackTrace();
}
}
}
).start();
adapter.notifyDataSetChanged();
dialog.dismiss();
}
It will not show up because the (blocking) work is done in another thread. That means, the
start()-method of theThread-class will not block.Ergo, you show the Dialog, the Thread is started and the dialog is immediately dismissed (and therefore closed).
Put the call to
dismiss()at the end of yourrun()-method and it should work just fine.The above might be working for you, but you should not use the
Thread-class directly. There are wrappers around it which are way more comfortable to use.In Android, if you want to do long-term work off the UI-Thread, you should use an
AsyncTask.