Search code examples
javaandroidandroid-studiotoastandroid-toast

how to show one time toast messages in android studio



I wanted to add a `toast message` when clicked on a button and I added it. Now I want show it only **one time**, that means the toast message will **not show again** if clicked on the button after the first time **also after a restart of app**.
Please help me!

Solution

  • You can do it with SharedPreferences that you store in another class like Utility.java:

    public class Utility {
    
        public static SharedPreferences preferences(Context context) {
            return PreferenceManager.getDefaultSharedPreferences(context);
        }
    
        public static Boolean hasSendToast(Context context) {
            return preferences(context).getBoolean("Toast", false);
        }
    
        public static void setSendToast(Context context, Boolean bool) {
            preferences(context).edit()
                    .putBoolean("Toast", bool).apply();
        }
    }
    

    And use it with your Toast inside the onClickListener in your MainActivity.java like this:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Button button = findViewById(R.id.button);
            button.setOnClickListener(v -> {
                if (!Utility.hasSendToast(getApplicationContext())) {
                    Toast.makeText(getApplicationContext(), "My Toast", Toast.LENGTH_SHORT)
                            .show();
                    Utility.setSendToast(getApplicationContext(), true);
                }
            });
        }
    }