android java onClick Could not execute method of the activity

前端 未结 4 1304
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 00:09

This is my first time working with the recyclerview and I am getting some errors about android:onClick=\"addItem\" here is what I get when I try to add a line o

4条回答
  •  不知归路
    2020-12-16 00:19

    The view in addItem(View v) is referring to the button only. The EditText object that you want is not in the button, it is in the button's parent view. If you try to access the object from the button view it will be null, because the button does not have it. Instead you need to access the object from the button's parent view.

    // Solution:
    public void addItem(View v) {
        View parentView = (View) v.getParent();
        EditText mText = (EditText) parentView.findViewById(R.id.textEt);
        Log.d("LOG", mText.getText().toString()));
    }
    

    I know that technically this does not solve the code in the question. But the code in the question has been changed from what produced the error so this would solve the original buggy code that actually produced the question. I am guessing that the original buggy code looked like this:

    // My guess this was the original buggy code
    // MainActivity.java
    public void addItem(View v) {
        EditText mText = (EditText) v.findViewById(R.id.textEt);
        Data dataToAdd = new Data(mText.getText().toString());
        mData.add(dataToAdd);
    }
    
    // MainActivity.xml
    
        
    
        

提交回复
热议问题