I want that this message is displayed only the first three times this button is clicked and never after that even if the application is restarted, I want to know the best way to achieve it. I plan to make a DB and enter values in that DB on button press and place my toast logic inside of an if statement. I want to know if there is a better way to do it without using a DB.
If by better you mean easier then you can use the SharedPreferences mechanism.
The shared preferences is basically a property set that is common for your entire activity or can be used by each activity separately.
class Listener implements OnClickListener{
final private SharedPreferences prefs;
Listener(SharedPreferences prefs){
this.prefs=prefs;
}
public void onClick(View view) {
int count = prefs.getInt("toastCount",0);
if(count>=3) return;
//do something else here
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("toastCount", count+1);
editor.commit();
}
}
and you can initiate this listnener using the getPreferences()
or getSharedPreferences()
methods from your activity
i think Shared Preferences is better than DB.
You just add count(int)
in shared Prefernces.
You can use this code:
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Toast.makeText(app.getBaseContext(),"Your message",
Toast.LENGTH_SHORT).show();
}
});
Consider persisting your data somewhere in the memory. Trivial data like this should not go into the database. It would be a bad decision.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.