Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Filipe S Jonson
Filipe S Jonson
10,381 Points

how do I make a toast appears just one time?

I want to show a Toast for the user at the start of the app, but because android activity lifecycle the toast keep showing up. what is the best way to stop that?

'''java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    mTraining = new Training();

    Toast.makeText(this, R.string.mainToast, Toast.LENGTH_SHORT).show();
}

'''

1 Answer

Kevin Faust
Kevin Faust
15,353 Points

You can use SharedPreferences to store a key/value pair in the app's data. So for example you can have a key "isPreviouslyOpened" and give it the value false at first and then when the user opens your app, you can set the value to true. You make the check in onCreate so see whether to show the Toast or not.

If you don't know what SharedPreferences are, there's a course on treehouse on different forms of storing data.

Filipe S Jonson
Filipe S Jonson
10,381 Points

that solution works, but I want to show the Toast every time the user opens the app. I tried to reset the SharedPreferences on the OnDestroy method, but i got the same bug, the toast shows up every time i rotate the screen

There's is a method after onDestroy?

''' java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mEditor = mSharedPreferences.edit();

    mTraining = new Training();

    isPreviouslyOpened = mSharedPreferences.getBoolean("isPreviouslyOpened", false);

    if(!isPreviouslyOpened) {
        Toast.makeText(this, R.string.mainToast, Toast.LENGTH_LONG).show();
        isPreviouslyOpened = true;
    }
}

@Override
protected void onStop() {
    super.onStop();
    mEditor.putBoolean("isPreviouslyOpened", isPreviouslyOpened).apply();
}

'''