I have a piece of code which connects to a server and then logs in. While these two tasks (connect to server and login) are being executed, a progress dialog appears.
final ProgressDialog pd = new ProgressDialog(getActivity());
pd.setIndeterminate(true);
pd.setCancelable(false);
// While connecting to the server, the dialog should say the following:
pd.setTitle("Connecting...");
pd.setMessage("Connecting to " + hostname + "...");
pd.show();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
// First task is executed. Progress dialog should say "Connecting..."
executeTask1();
// When the first task (connecting to server) is ready, I want the title
// and the message of the progress dialog to be changed into this:
pd.setTitle("Logging in"); //// MARKED LINE, see below. ////
pd.setMessage("Trying to log in to server...");
// Second task is executed.
executeTask2();
// Shows a screen and dismisses the ProgressDialog.
showScreen(ScreenConstant.LIST_RESIDENTS);
pd.dismiss();
}
catch (Exception exc) { }
}
}
But I ran into two problems:
- A
RuntimeException
is raised when the MARKED LINE (see above) is executed: "Only the original thread that created a view hierarchy can touch its views" - The login task gets a response from the server, but this response is asynchronous.
I want a ProgressDialog
to appear with the text "Connecting..." while the connection attempt is being executed. After the connection is successful, I want the text of the progress dialog to be changed into "Logging in...", while the login attempt is being performed.
Now how should I achieve this?
EDIT
Notice that executeTask2()
triggers a task to be run in a different thread; it sends a login request to the server, therefore I need to wait until that thread signals me when it's ready.