I have arraylist (mNamelist), which has items (NameItem), and those items contain 2 variables (String and int). I also have an input field, where the user inserts new names to the list.
I need to check every item in a list, and if the user gave name is not in any of those items, then it can add an item. If it finds a match, it should give Toast and stop looping immediately.
something I tried:
private void addItem(int position) {
/** Get user input (name) **/
textAdd = findViewById(R.id.name_input);
/** Check if that name already on a list **/
for (int i = 0; i < mNameList.size(); i++) {
/** Check namelists item, and in that item String variable named getText1 and check if it match to the name that user gave **/
if (mNameList.get(i).getText1() == textAdd.toString().trim()) {
/** If match, give toast and stop looping **/
Toast toast= Toast.makeText(getApplicationContext(),
"This name is already on a list...", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
break;
} else {
/** If no matches, add name to the list **/
mNameList.add(position, new NameItem(textAdd.getText().toString().trim()));
sortArrayList();
saveData();
mAdapter.notifyItemInserted(position);
textAdd.getText().clear();
}
}
}
Soon I realized that problem here is that every time it won't get a match, it tries to add that item. What it should do is that AFTER ALL items been checked AND none match found, only then it should add that new name ONCE, not in every loop. Also if it finds a match, it should give that Toast and stop looping immediately.