coder4lyf
coder4lyf

Reputation: 927

Make an alert only appear when app is opened

Is there a way to make an alert only appear when the app is opened? I'm creating an alert in onStart() in my MainActivity and whenever I go back to that activity in the app, it shows the alert again which can be annoying to the user. Or is there a way to create a "got it" button and then turn off the alert? Here is my code:

protected void onStart() {
    super.onStart();
    new AlertDialog.Builder(this)
            .setTitle("Instructions")
            .setMessage("Hello! To begin, select a map from the list to train with. Make sure" +
                    " you are on the correct floor.")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(R.drawable.ic_launcher)
            .show();

}

Upvotes: 0

Views: 95

Answers (2)

Mohamed Hatem Abdu
Mohamed Hatem Abdu

Reputation: 468

This is because when another activity comes to foreground upon your MainActivity makes your activity goes to OnPause(). Then when you go back to your MainActivity. The system calls onStart() again. See The activity life cycle

-First Solution

public class TestActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        showAlertDialog();
    }
}

private void showAlertDialog() {
    // code to show alert dialog.
}

}

-Second Solution

public class TestActivity extends ActionBarActivity {

private static boolean isAlertDialogShownBefore = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!isAlertDialogShownBefore) {
        showAlertDialog();
        isAlertDialogShownBefore = true;
    }
}

private void showAlertDialog() {
    // code to show alert dialog.
}

@Override
public void onBackPressed() {
    isAlertDialogShownBefore = false;
    super.onBackPressed();
}

}

Upvotes: 1

Rajesh Batth
Rajesh Batth

Reputation: 1662

Put that code in onCreate method of your activity. Check for saveInstanceState for null, if it is then show your alertDialog

Upvotes: 0

Related Questions