Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I going to contribute my approach to handling this rotation issue. This may not be relevant to OP as he's not using <code>AsyncTask</code>, but maybe others will find it useful. It's pretty simple but it seems to do the job for me:</p> <p>I have a login activity with a nested <code>AsyncTask</code> class called <code>BackgroundLoginTask</code>.</p> <p>In my <code>BackgroundLoginTask</code> I don't do anything out of the ordinary except to add a null check upon calling <code>ProgressDialog</code>'s dismiss:</p> <pre><code>@Override protected void onPostExecute(Boolean result) { if (pleaseWaitDialog != null) pleaseWaitDialog.dismiss(); [...] } </code></pre> <p>This is to handle the case where the background task finishes while the <code>Activity</code> is not visible and, therefore, the progress dialog has already been dismissed by the <code>onPause()</code> method.</p> <p>Next, in my parent <code>Activity</code> class, I create global static handles to my <code>AsyncTask</code> class and my <code>ProgressDialog</code> (the <code>AsyncTask</code>, being nested, can access these variables):</p> <pre><code>private static BackgroundLoginTask backgroundLoginTask; private static ProgressDialog pleaseWaitDialog; </code></pre> <p>This serves two purposes: First, it allows my <code>Activity</code> to always access the <code>AsyncTask</code> object even from a new, post-rotated activity. Second, it allows my <code>BackgroundLoginTask</code> to access and dismiss the <code>ProgressDialog</code> even after a rotate.</p> <p>Next, I add this to <code>onPause()</code>, causing the progress dialog to disappear when our <code>Activity</code> is leaving the foreground (preventing that ugly "force close" crash):</p> <pre><code> if (pleaseWaitDialog != null) pleaseWaitDialog.dismiss(); </code></pre> <p>Finally, I have the following in my <code>onResume()</code> method:</p> <pre><code>if ((backgroundLoginTask != null) &amp;&amp; (backgroundLoginTask.getStatus() == Status.RUNNING)) { if (pleaseWaitDialog != null) pleaseWaitDialog.show(); } </code></pre> <p>This allows the <code>Dialog</code> to reappear after the <code>Activity</code> is recreated.</p> <p>Here is the entire class:</p> <pre><code>public class NSFkioskLoginActivity extends NSFkioskBaseActivity { private static BackgroundLoginTask backgroundLoginTask; private static ProgressDialog pleaseWaitDialog; private Controller cont; // This is the app entry point. /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (CredentialsAvailableAndValidated()) { //Go to main menu and don't run rest of onCreate method. gotoMainMenu(); return; } setContentView(R.layout.login); populateStoredCredentials(); } //Save current progress to options when app is leaving foreground @Override public void onPause() { super.onPause(); saveCredentialsToPreferences(false); //Get rid of progress dialog in the event of a screen rotation. Prevents a crash. if (pleaseWaitDialog != null) pleaseWaitDialog.dismiss(); } @Override public void onResume() { super.onResume(); if ((backgroundLoginTask != null) &amp;&amp; (backgroundLoginTask.getStatus() == Status.RUNNING)) { if (pleaseWaitDialog != null) pleaseWaitDialog.show(); } } /** * Go to main menu, finishing this activity */ private void gotoMainMenu() { startActivity(new Intent(getApplicationContext(), NSFkioskMainMenuActivity.class)); finish(); } /** * * @param setValidatedBooleanTrue If set true, method will set CREDS_HAVE_BEEN_VALIDATED to true in addition to saving username/password. */ private void saveCredentialsToPreferences(boolean setValidatedBooleanTrue) { SharedPreferences settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE); SharedPreferences.Editor prefEditor = settings.edit(); EditText usernameText = (EditText) findViewById(R.id.editTextUsername); EditText pswText = (EditText) findViewById(R.id.editTextPassword); prefEditor.putString(USERNAME, usernameText.getText().toString()); prefEditor.putString(PASSWORD, pswText.getText().toString()); if (setValidatedBooleanTrue) prefEditor.putBoolean(CREDS_HAVE_BEEN_VALIDATED, true); prefEditor.commit(); } /** * Checks if user is already signed in */ private boolean CredentialsAvailableAndValidated() { SharedPreferences settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE); if (settings.contains(USERNAME) &amp;&amp; settings.contains(PASSWORD) &amp;&amp; settings.getBoolean(CREDS_HAVE_BEEN_VALIDATED, false) == true) return true; else return false; } //Populate stored credentials, if any available private void populateStoredCredentials() { SharedPreferences settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE); settings.getString(USERNAME, ""); EditText usernameText = (EditText) findViewById(R.id.editTextUsername); usernameText.setText(settings.getString(USERNAME, "")); EditText pswText = (EditText) findViewById(R.id.editTextPassword); pswText.setText(settings.getString(PASSWORD, "")); } /** * Validate credentials in a seperate thread, displaying a progress circle in the meantime * If successful, save credentials in preferences and proceed to main menu activity * If not, display an error message */ public void loginButtonClick(View view) { if (phoneIsOnline()) { EditText usernameText = (EditText) findViewById(R.id.editTextUsername); EditText pswText = (EditText) findViewById(R.id.editTextPassword); //Call background task worker with username and password params backgroundLoginTask = new BackgroundLoginTask(); backgroundLoginTask.execute(usernameText.getText().toString(), pswText.getText().toString()); } else { //Display toast informing of no internet access String notOnlineMessage = getResources().getString(R.string.noNetworkAccessAvailable); Toast toast = Toast.makeText(getApplicationContext(), notOnlineMessage, Toast.LENGTH_SHORT); toast.show(); } } /** * * Takes two params: username and password * */ public class BackgroundLoginTask extends AsyncTask&lt;Object, String, Boolean&gt; { private Exception e = null; @Override protected void onPreExecute() { cont = Controller.getInstance(); //Show progress dialog String pleaseWait = getResources().getString(R.string.pleaseWait); String commWithServer = getResources().getString(R.string.communicatingWithServer); if (pleaseWaitDialog == null) pleaseWaitDialog= ProgressDialog.show(NSFkioskLoginActivity.this, pleaseWait, commWithServer, true); } @Override protected Boolean doInBackground(Object... params) { try { //Returns true if credentials were valid. False if not. Exception if server could not be reached. return cont.validateCredentials((String)params[0], (String)params[1]); } catch (Exception e) { this.e=e; return false; } } /** * result is passed from doInBackground. Indicates whether credentials were validated. */ @Override protected void onPostExecute(Boolean result) { //Hide progress dialog and handle exceptions //Progress dialog may be null if rotation has been switched if (pleaseWaitDialog != null) { pleaseWaitDialog.dismiss(); pleaseWaitDialog = null; } if (e != null) { //Show toast with exception text String networkError = getResources().getString(R.string.serverErrorException); Toast toast = Toast.makeText(getApplicationContext(), networkError, Toast.LENGTH_SHORT); toast.show(); } else { if (result == true) { saveCredentialsToPreferences(true); gotoMainMenu(); } else { String toastText = getResources().getString(R.string.invalidCredentialsEntered); Toast toast = Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT); toast.show(); } } } } } </code></pre> <p>I am by no means a seasoned Android developer, so feel free to comment.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload