how to prevent execution of same thing again and again - java

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();
}

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;
}
}

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

Related

How to update data from listview if the condition were met android java

Hi Iam creating this app were you input Name and it automatically put the Time-inon the listview with current time. Now, if the user were to put the same Name, the system then recognized it to avoid duplication.
Here is the code for condition
getTime();
String fnlAddName = finalTextName+"\n"+formattedDate+"\n"+strTime;
if (names.indexOf(finalTextName) > -1){
//the system recognized the same input
String beforeName = listView.getItemAtPosition(position).toString();
names.add(beforeName+"\n"+strTime);
myAdapter.notifyDataSetChanged();
}else{
names.add(fnlAddName);
myAdapter.notifyDataSetChanged();
dialog.cancel();
position = position+1;
}
Now, I already achieved to detect same input from the user. What I want now is, I want to take that same data from the list (with also the time) and add another current time. So the list must update from "Name+1stCurrentTime" to "Name+1stCurrentTime+2ndCurrentTime"
Your code should look something like this
if (names.indexOf(finalTextName) > -1){
//the system recognized the same input
int index = names.indexOf(finalTextName);
names.set(index, names.get(index) + "\n" + strTime);
myAdapter.notifyDataSetChanged();
}else{
names.add(fnlAddName);
myAdapter.notifyDataSetChanged();
dialog.cancel();
position = position+1;
}
With the indexOf method you can get the position of the list that contains the name, then we replace it, I hope this helps you.

Want to output my entered names by JOptionPane outside the loop, JAVA

Basically i want to enter the names as long as i don't cancel the InputMessageDialog, then i want to asign my names to variable created before and print them out at the end in the MessageDialog. I was trying some stuff outside the loop but got the notificacion that "value 'names' is always 'null'"
String names;
while (true) {
names = JOptionPane.showInputDialog(null, "ENTER THE NAMES");
if (names == null) {
JOptionPane.showMessageDialog(null, "ENTRY CANCELED!");
break;
} else {
}
}
JOptionPane.showMessageDialog(null, "YOUR NAMES: " + names);
Your code is pretty close to what you describe as your goal – the primary thing missing is that you need to keep track of the various values along the way, and print them at the end.
The code you posted will loop again and again asking for a single value (which you are storing into String names - a little confusing choice for variable name, since it contains only one name input). As you found, when the user hits the cancel button (to end the loop), it sets names to null. The final step shows a dialog box with the last value for names (which is always null).
Here's a program that:
loops until the user hits the "cancel" button (which would set input to be null), or if they enter a blank value – this allows the user to exit by simply hitting return without typing anything
adds all non-empty input values to a java.util.Set – this is an arbitrary choice, use whatever data structure is appropriate for your program
shows a final dialog with the contents of the set
import javax.swing.*;
import java.util.HashSet;
import java.util.Set;
public class t {
public static void main(String[] args) {
Set<String> values = new HashSet<>();
while (true) {
String input = JOptionPane.showInputDialog(null, "enter something");
if (input != null && !input.isEmpty()) {
values.add(input);
} else {
break;
}
}
JOptionPane.showMessageDialog(null, "all values: " + values);
}
}
If I run with the following input:
one
two two
three three three
<blank>
Then the final dialog message is:
all values: [one, two two, three three three]
Note that a java.util.Set doesn't necessarily return items in any specific order, it just happens to have worked out that way in this example.

Storing text as an arraylist from JTextArea

I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}

Exception handling when dealing with user input for a beginner

I have to do a little program based in a shop, I have to add new clients to the shop customer collection, new items to the shop stock, edit them etc, so I use user input(scanner) to create this new objects. I have all the methods I need for this already without exceptions.
I would like some simple java exception handling for when the user introduces a string were he is supposed to enter a integer or viceversa.
For example if I'm executing a method to create a item for the shop and when I ask the user to introduce the stock(integer) the user types hello instead of a number the program crashes, I would like to handle the exception, show a error message, don't create the object and relaunch the item creation method from the beggining(or relaunch the submenu it was right before)
should I use try and catch? the method in try, when it fails catch throws message of error and relaunches the item creation menu? How should i do this? I've been searching and found a interesting method for integers here:
Exception Handling for no user input in Java
The problem is I don't know how I could handle possible exceptions for when introducing the ID for the user(which would be a string composed of 8 numbers and a letter like for example: 13234354A, so how could I show a error if a user introduces "sjadsjasdj" as a ID instead of something sort of realistic ) or some other things like handling exceptions for a few enum or boolean variables I use when creating this objects.
I've been looking in this site and searching google but I haven't found what I need or are more complex than what I understand with my little knowledge, also English is not my native language so my searches may be a little off.
Thanks for your time!
When you are reading the input just read in the the entire ID 123A for example and verify that each character is valid using for example Character.isDigit() and Character.isLetter(). With a 4 letter case
import java.util.Scanner;
public class Test {
public static void main(String[]args) {
boolean flag = false;
Scanner kb = new Scanner(System.in);
while(!flag) {
String id = kb.next();//To get the next word
flag = true;//by default its assumed to be valid input
if(id.length() == 4) {
for(int i = 0; i < 3; i++) {
if(!Character.isDigit(id.charAt(i))) {
flag = false;
}
}
if(!Character.isLetter(id.charAt(3))) {
flag = false;
}
}
else {
flag = false;
}
System.out.println("ID is "+ (flag == true?"Valid":"Invalid"));
}
}
}
Output
1234
ID is Invalid
123A
ID is Valid
You could throw your own error at the end if you want or just loop back to the beginning to take a new input.

How to validate phone number in android application?

I am working on android. In my app users will register by entering their phone number in edittext. This phone number is then saved in database. Now when the user login with the app, I am getting the list of contacts from his mobile and comparing that with the people who register with this app. If the number in the contacts list matches with the number in the database, then I need to display those numbers in listview. Here the problem is if the user save his number with +91 or with 0 before his contact then the number in the database is not matching with the contact. At that time the numbers are not displaying.
For this issue, Do we need to keep any alert before entering the number in edit text? For example in edit text I gave, Ph no: 8923458128 and the saved it in database. Now I logged in with this number and my contacts list for suppose
9823484586
+919988334856
Lets say the above 2 numbers are stored in database. But the 2nd contact , the user entered as 9988334856 without +91. Then finally in the listview instead of 2 numbers only 1 number is displaying as the second number is not matching with database number.
How can I solve this issue? Please help me in this regard.
If you are fetching all phones from DB, then you can use below code to match entered phone with phone from DB using PhoneNumberUtils.compare()
It compares phone numbers a and b, return true if they're identical
enough for caller ID purposes.
private String getMatchedPhones(ArrayList<String> contactsFromDB, String phoneToMatch) {
// Iterate all numbers and match
for (String numberFromDb : contactsFromDB) {
if (PhoneNumberUtils.compare(numberFromDb, phoneToMatch)) {
return phoneToMatch; // Or numberFromDb
}
}
return null; // Or can custom msg. If not matched.
}
I think best way to do it create your table with 4 column-
1)id
2)name(if needed)
3)country-code
4)phone number
And now on your UI prefix country code in a spiner and give phone-number type of field in a textview. And in your database use integer value to store number.
And from matching your phone number just pass this query-
1)phoneNumber = phoneNumberEditText.getText().toString();
2)
// Reading all contacts from database
List<Contacts> number = db.getAllNumber();
for (final Contacts cn : number) {
if ((phoneNumber.equals(cn.getNumber()){
//do what you want
}
}
Thanks!Hope it will help you.
Put these two lines in your XML file at that phone number edit text field
android:inputType="numberDecimal"
android:maxLength="10"
then he could not enter more than 10 numbers and only he should enter numbers.
you can take country code in one more text field and validate with it.
For an Mobile number validation android provide InBuilt Patterns.But it only works in API level 8 and above.Try below one line code.
/* method for phone number validation */
private Boolean Number_Validate(String number)
{
return !TextUtils.isEmpty(number) && (number.length()==10) && android.util.Patterns.PHONE.matcher(number).matches();
}
you can call this mehtod by passing number in parameter,it return either true or false.
Number_Validate(number);
Hope you get your answer.
Thanks.
Use TEXT not Int in your database. When you use Int, if the first number is 0 it will disregard so just use TEXT.
private boolean phvalidator(String ph2) {
// TODO Auto-generated method stub
String expression = "^[0-9-1+]{10,15}$";
CharSequence inputStr = ph;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
return (matcher.matches())? true : false;
try this
final String mobile = emobile.getText().toString();
if (!isValidMobile(mobile)){
emobile.setError("Invalid Mobile");
}
private boolean isValidMobile(String mobile) {
if (!TextUtils.isEmpty(mobile)) {
return Patterns.PHONE.matcher(mobile).matches();
}
return false;
}

Categories

Resources