user2903200
user2903200

Reputation: 710

Android : Setvisibility to visible causes nullpointerexception on button

This seems to have been asked in stackoverflow a bit before with no convincing answers for most questions. anyways, i attempt again. I have an Android App where am displaying a list where each row has an Edittext and Button component as seen below

enter image description here

The Edittext is non-editable when the view appears. I do this with the code below:

private void setNameAsEditable (View rowView, boolean setToEditable) {

    EditText textView = (EditText) rowView
            .findViewById(R.id.edittext_name);
    textView.setFocusableInTouchMode(setToEditable);
    textView.setFocusable(setToEditable);

    ImageButton button = (ImageButton) rowView
            .findViewById(R.id.button_save_name);

            if ( setToEditable ) {

                    button.setVisibility (View.VISIBLE);  // nullpointerexception here
    } else {
        button.setVisibility (View.GONE);
    }

When I long-press, and setToEditable is true, it throws nullpointerexception in the line indicated above. it doesn't seem to find the button component. However, 'button.setVisibility (View.GONE);' is executed when setToEditable is false without any issue.

Can someone please help?

Upvotes: 1

Views: 1998

Answers (2)

Gabe
Gabe

Reputation: 1249

rowView appears to be your EditText while you actually want the parent view that has the button inside of it. If you call findViewById and the id doesn't exist inside of that view, it will return null.

Upvotes: 1

Chintan Khetiya
Chintan Khetiya

Reputation: 16142

I think issue is initialization of view control. You should initialize EditText & ImageButton at the top.

      EditText textView;
      ImageButton button ;
      ...
      ...
      ...
      EditText textView = (EditText) rowView.findViewById(R.id.edittext_name);
      ImageButton button = (ImageButton) rowView.findViewById(R.id.button_save_name);

And next thing is try to write your code in try & catch block so you get exact idea what is wrong and where is bug.

Upvotes: 0

Related Questions