I am coding an app that give me some problems. I have an activity A with a button. When the user presses the button, it retrieves data from the Internet using an AsyncTask class, and when the data is retrieved, the AsyncTask class calls a method declared in activity A that starts a new activity B.
But this has a problem I don't know how to fix. If the user presses the button twice (or more than once), the data is retrieved two times and activity B is launched twice. So, once I am in activity B, when I press the back button that instance of Activity B is destroyed but I'm still in the activity B (because it was launched twice).
Some code from the AsyncTask class which download the data:
@Override
protected String doInBackground(String... urls) {
try {
String data = downloadUrl(urls[0]);
return downloadUrl(urls[0]);
} catch (IOException e) {
return m_errorCODE;
}
}
@Override
protected void onPostExecute(String result) {
((MainActivity) mParentActivity).displayInfo(result);
}
Method displayInfo() from MainActivity which launches the activity B:
public void displayInfo(String result) {
int duration = Toast.LENGTH_LONG;
Toast toast = null;
setSupportProgressBarIndeterminateVisibility(false);
if (result == "404 ERROR") {
toast = Toast.makeText(getBaseContext(), R.string.error_file_not_found, duration);
toast.show();
} else if (result == "CONNECTION_ERROR") {
toast = Toast.makeText(getBaseContext(), R.string.error_connection, duration);
toast.show();
} else {
Intent intent = new Intent(this, DisplayInfo.class);
m_data = result;
intent.putExtra(DOWNLOADED_DATA, m_data);
intent.putExtra(FORMAT_OK, Boolean.toString(m_formatOK));
intent.putExtra(URL_FILE, urlFile);
startActivity(intent);
}
}
So I have three problems:
- How can I download the data only once?
- How can I open activity B only once?
- How can I know in my Activity A is still alive when it executes onPostExecute()?
To solve #2 I tried using intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) before starting activity B. It opens only one activity B, but if I press back, activity A starts again another instance of activity B.
Do I need to paste more code? Thanks in advance.