I have been reading a good amount about AsyncTasks but I can't figure something out. I have an AsyncTask that I start that is used for an HttpURLConnection for a request from my database. The database work is done in doInBackground() and I have a ProgressDialog that runs on the UI thread that just shows that it is loading. Once the doInBackground() is complete though, my code continues even though I have some things in the onPostExecute() that need to happen before the code can continue.
Is there a way to keep the AsyncTask asynchronous so I can run the ProgressDialog and do the database work in doInBackgroun() at the same time and also have it wait to continue until onPostExecute() has been called?
To clarify:
I cannot just call a function in the onPostExecute() call. At launch an AlertDialog is opened in order for the user to input their username and password so they can login. When they hit login, the AsyncTask is run. I need the AlertDialog to know when the onPostExecute() is complete as well in order to close it. Otherwise I'll be stuck with it.
Here is the code for the AlertDialog in the beginning:
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setCancelable(false);
final EditText usernameInput = new EditText(context);
usernameInput.setHint("Username");
final EditText passwordInput = new EditText(context);
passwordInput.setHint("Password");
passwordInput.setTransformationMethod(PasswordTransformationMethod.getInstance());
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(usernameInput);
layout.addView(passwordInput);
alert.setView(layout);
alert.setTitle("Login");
alert.setPositiveButton("Login", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
String username = usernameInput.getText().toString();
String password = passwordInput.getText().toString();
if (username != "" && password != "")
{
Database database = new Database(currActivity);
database.Login(username, password);
if (database.IsLoggedIn())
{
SharedPreferences prefs = currActivity.getSharedPreferences("Preferences", currActivity.MODE_PRIVATE);
prefs.edit().putBoolean("Logged In", true).commit();
dialog.cancel();
}
else ShowLoginAlert(context);
}
}
});
alert.show();
Here is my code for the login:
public void Login(String username, String password)
{
try
{
new AsyncLogin().execute(username, password).get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e1)
{
e1.printStackTrace();
}
}
private class AsyncLogin extends AsyncTask<String, String, String>
{
private static final int READ_TIMEOUT = 1000000;
private static final int CONNECTION_TIMEOUT = 1000000;
private URL url = null;
private HttpURLConnection conn = null;
ProgressDialog loading = new ProgressDialog(currActivity);
@Override
protected void onPreExecute()
{
super.onPreExecute();
loading.setMessage("\tLoading...");
loading.setCancelable(false);
loading.show();
}
@Override
protected String doInBackground(String... params)
{
try
{
url = new URL("http://mysite/myscript.php");
}
catch (MalformedURLException e)
{
e.printStackTrace();
return "Malformed URL Exception.";
}
try
{
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", params[0])
.appendQueryParameter("password", params[1]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
conn.connect();
}
catch (IOException e1)
{
e1.printStackTrace();
return "Connection Exception.";
}
try
{
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
{
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
return result.toString();
}
else return "Unsuccessful data retrieval.";
}
catch (IOException e2)
{
e2.printStackTrace();
return "Response Exception.";
}
finally
{
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
loading.dismiss();
if (result.equalsIgnoreCase("true"))
{
// Successfully logged in
SetIsLoggedIn(true);
Toast.makeText(currActivity, "Successfully logged in.", Toast.LENGTH_LONG).show();
}
else
{
// Incorrect credentials
SetIsLoggedIn(false);
Toast.makeText(currActivity, "Incorrect credentials.", Toast.LENGTH_LONG).show();
}
}
}