Reputation: 906
When my app starts up, but has not yet loaded a file, the user gets a Toast
when he clicks the button. It takes about half a second to load, so since he is able to click the button multiple times, it is possible for multiple Toast
s to get displayed after one another.
I tried setting up a Toast
object as an attribute of my MainActivity
's class, but it crashes with NullPointerException
s.
The implementation:
Toast lToast;
(...)
public void exampleMethod() {
if(lToast == null) {
lToast.makeText(this, "Noch kein Sound geladen.", Toast.LENGTH_SHORT);
lToast.show();
}
}
Is it possible to prevent Toast
s from queueing up without the need to have a local attribute? And if not, what did I do wrong?
Upvotes: 1
Views: 740
Reputation: 5176
WIIIJBD has given a wonderful answer.
However in your case instead of blocking the Toast
you can disable the Button
.
You can disable the button in onClick()
and then again set your onClickListener()
somewhere when you get your callback after you are done loading whatever you intend to load.
Upvotes: 1
Reputation: 6164
I am not sure what you mean by "without a local attribute", but digging in to the android code you will find that the long and short delays are as follows
private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds
so when you launch your toast, if you capture the timestamp like so
long lastToastTimestamp = System.currentTimeMillis();
you should be able to prevent multiple toast messages
if (System.currentTimeMillis() - lastToastTimestamp > 2000)
{
lastToastTimestamp = System.currentTimeMillis();
Toast.makeText(this, "Noch kein Sound geladen.", Toast.LENGTH_SHORT).show();
}
or what about this
make the field:
Toast mToast = null;
and then the code:
if (mToast == null)
{
mToast = Toast.makeText(context, "Noch kein Sound geladen.", Toast.LENGTH_SHORT);
mToast.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run()
{
mToast = null;
}
}, 2000);
}
If you wanted to make it even more complex you could create your own queue, and only insert new toasts that will be displayed at the expiration of the previous one, if the text given the toast is different from the current one and all the ones in the queue.
Upvotes: 3
Reputation: 3191
I know that your question wasn't that but anyway... A library I use and recommend using is Crouton, which is a Activity strong-dependent library just like Toast, with a lot of customization !
Hope it helps !
Upvotes: 0
Reputation: 2769
Toast.makeText(...)
is static member of Toast
class returning Toast
instance. You've declared Toast lToast
object but you didnt initialize it.
Change:
lToast.makeText(this, "Noch kein Sound geladen.", Toast.LENGTH_SHORT);
to
lToast = Toast.makeText(this, "Noch kein Sound geladen.", Toast.LENGTH_SHORT);
I'm not sure if this will work, but it will prevent raising NullPointerException
.
Upvotes: 2