首页 > 解决方案 > Java: Loop thought the list, then check the results with if else

问题描述

I have situation where I have Arraylist, which has name items in it. I need to loop through that namelist which check if the new name that user gave, is already on a list or not. If it is, just give toast to notify user that name is already there, or if it isn't, then add name to the list.

This is what I have:

public class ActivityPlayers extends AppCompatActivity {
    public static ArrayList<NameItem> mNameList;

    private Button buttonAdd;
    private EditText textAdd;

    private int checkNumber;


        /** When "add" button been clicked... **/
        textAdd = findViewById(R.id.name_input);
        buttonAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                /** Loop the list **/
                for (int i = 0; i < mNameList.size(); i++) {

                    /** Check if user input match to any name in list 
                    and if it does...**/
                    if (mNameList.get(i).getText1().equals(textAdd.toString().trim())) {
                        checkNumber = 1;
                        break;
                    } else {
                        /** If it doesn't **/
                        checkNumber = 0;
                    }
                }

                /** if checkNumber is still 0 **/
                if (checkNumber == 0) {
                    /** Close soft keyboard **/
                    InputMethodManager input = (InputMethodManager)
                            getSystemService(Context.INPUT_METHOD_SERVICE);
                    input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);

                    /** ...add a name to the namelist **/
                    addItem(0);
                } else {
                    /** if name in a list == name from input, give toast **/
                    Toast toast = Toast.makeText(getApplicationContext(),
                            "Name is already on a list", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();
                }
            }
        });

Any ideas why this won't work? It only adds the names to the list, even tho it already exists... but it never detects duplicates...

标签: javaandroid

解决方案


if (mNameList.get(i).getText1().equals(textAdd.toString().trim()))

在上面的代码行中,您将第i个列表元素与 EditText 本身的字符串表示形式进行比较,而不是与其 Text 字段进行比较。而不是textAdd.toString(),您应该使用textAdd.getText().

与问题无关,但我建议使用boolean变量来表示代码中的逻辑标志,而不是整数计数。
在上面的例子中,它会是这样的:

private boolean nameInList = false;
//...
if (...) {
    nameInList = true;
    break;
}
//...
if (nameInList) {
    //...
} else {
    //...
}

推荐阅读