1

I'm trying to create simple toast which will show only at the third time, when we open the app. Tried to google that question, but nothing found. Help me please.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Context context = getApplicationContext();
    CharSequence text = "Hello toast!";
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

}

CogsMaster
  • 25
  • 4
  • 1
    Why don't you make it simple Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); – Hasan May 05 '21 at 08:17
  • Well for that you could have an counter in shared prefrences and increment it when user closes your app. and if the value of that key is 2 that means its 3rd time show it using if condition – Akash Pal May 05 '21 at 12:25

1 Answers1

0

So you need a counter the increments on starting the app and also gets checked if it reached the number 3. For this question I assume that MainActivity will be the first Activity that will be shown on startup and it is the only activity. Otherwise you must do some adjustments, when it is possible to navigate to another Activity and back.

private final String PREF_COUNTER_KEY = "PREF_COUNTER_KEY";

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   
   // load counter 
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);  
   int startupCounter = prefs.getInt(PREF_COUNTER_KEY, 0);  
   startupCounter++;

   if(startupCounter > 2){
      Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show();
   }  
 
   // save incrementation
   SharedPreferences.Editor prefsEditor = prefs.edit();
   prefsEditor.putInt(PREF_COUNTER_KEY, counter);
   prefsEditor.apply();

}
Marcel Hofgesang
  • 951
  • 1
  • 15
  • 36