0

I want my user to see a Toast upon my app's start and never again until the app has been killed and then deliberately started up again (not merely restored from being in background.)

So I set a boolean to let me know if toast has been eaten yet and show the toast if it hasn't and set the boolean to eaten, but rotating the device resets everything, even that boolean. How do I make it so that the boolean doesn't get reset on rotate?

Philippe Le Point
  • 255
  • 1
  • 3
  • 13

3 Answers3

4

Save the current state of the boolean using the savedInstanceState parameter.

Refer to this post: Saving Android Activity state using Save Instance State.

Community
  • 1
  • 1
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
1

See the code below:

public class YourActivity extends Activity {

private Boolean showToast=true;

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

   if(savedInstanceState==null){//  show your toast here}
   else{
      if(showToast){// show your toast here}
     }

}



  @Override
  public void onSaveInstanceState(Bundle savedInstanceState) {
     super.onSaveInstanceState(savedInstanceState);

         savedInstanceState.putBoolean("Toast_shown", true);

  }


     @Override
     public void onRestoreInstanceState(Bundle savedInstanceState) {
       super.onRestoreInstanceState(savedInstanceState);

       boolean myBoolean = savedInstanceState.getBoolean("Toast_shown");
       this.showToast=!myBoolean;

       }

}

NavinRaj Pandey
  • 1,674
  • 2
  • 26
  • 40
0

You can do this in many ways

Simplest solution:: Use a flag to achieve your goal

public class MainActivity extends Activity {

     boolean toastFlag=false;

       @Override
       protected void onCreate(Bundle savedInstanceState) 
       {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         if(toastFlag==false){
         Toast.makeText(getApplicationContext(), "Hi-I-AM-A-TOAST-MESSAGE",Toast.LENGTH_LONG).show();
         toastFlag=true;
       }

     @Override
        public void onSaveInstanceState(Bundle savedInstanceState) 
        {
          super.onSaveInstanceState(savedInstanceState);
          savedInstanceState.putBoolean("MyBoolean", toastFlag);
        }

        @Override
        public void onRestoreInstanceState(Bundle savedInstanceState) 
        {
          super.onRestoreInstanceState(savedInstanceState);
          toastFlag= savedInstanceState.getBoolean("MyBoolean");
        }     

}

Devrath
  • 42,072
  • 54
  • 195
  • 297
  • Thank you that works, but I have to retrieve the boolean's value in the onCreate() method as well. If it's not set then I assume false and pop the toast. – Philippe Le Point Aug 16 '14 at 05:31