I have made an application that whenever a user types a particular word it toast a massage now I want to add a feature that if the user has typed the particular word continuously many times in a particular time it will consider it once only and toast the massage ones only.
The code
if ( string.equals("help") ) {
Toast.makeText(getApplicationContext(), "we are here to help", Toast.LENGTH_SHORT).show();
}
CodePudding user response:
Use a global String variable let's name it as lastText
and check whether input text is the same as last text.
UPDATE for time tracking
private String lastText = ""; // Global for all class members
private long lastTextTime = 0; // Global
//...
// May be more code goes here
//...
if ( string.equals("help") && !string.equals(lastText) ) {
// Check whether 5 min has elapsed to show the toast message
if(System.currentTimeMillis - lastTextTime > (5*60*1000)) {
Toast.makeText(getApplicationContext(), "we are here to help",
Toast.LENGTH_SHORT).show();
// If the program reach here save this string as a last text for the next check
lastText = string;
lastTextTime = System.currentTimeMillis;
}
}
CodePudding user response:
You can add already typed words to a list, and when the user types a word, you can iterate through this list and check if "word" is already was typed, and then if "false" - show toast.
Alternative solution - you can create a local SQLite database (using Room persistence library), it will allow you to save values even if user restart/exit app, but it will require more coding and fixing nuances