-1

I have made a custom EditText so that I can overwrite what happens when the back key is pressed while there is a keyboard on the screen. (Based on an answer to this linked question)

What I want to do when the back key is pressed is four things: set a boolean, change a custom EditText's text, change a Button's text, and change a TextView's visibility. All four of these are in a different file (which I believe may be what is causing the problem). But I can find them, and adjust two of them without crashes.

public class NiceEditText extends EditText {
    Context context;

    public NiceEditText(Context contx, AttributeSet attrs){
        super(contx,attrs);
        this.context = contx;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (ListActivity.addedTitle) ListActivity.addedTitle = false;
            NiceEditText editItem = (NiceEditText) findViewById(R.id.editItem);
            editItem.setText("");
            Button niceButton = (Button) findViewById(R.id.niceButton);
//            niceButton.setText(R.string.addItem);
            TextView addingTitle = (TextView) findViewById(R.id.addingTitle);
//            addingTitle.setVisibility(View.INVISIBLE);
        }
        return super.onKeyPreIme(keyCode, event);
    }
}

The two commented lines cause the app to crash due to a NullPointerException. I wonder if this is because it could not find either the Button or the TextView, but it could find the NiceEditText and change it.

Q: How can I change the Button's text and the TextView's visibility?

Community
  • 1
  • 1
Chronicle
  • 1,565
  • 3
  • 22
  • 28

2 Answers2

0
// niceButton.setText(R.string.addItem);

This line is what cause the NullPointerException error. Change it to:

niceButton.setText(getResources().getString (R.string.addItem));
cw fei
  • 1,534
  • 1
  • 15
  • 33
0

I had to set an activity variable like this:

public void setActivity(Activity a){
    this.activity = a;
}

Which was called in the onCreate of the actual activity. Then in the onKeyPreIme I had to call the getViewByIds like this:

Button niceButton = (Button) activity.findViewById(R.id.niceButton);
TextView addingTitle = (TextView) activity.findViewById(R.id.addingTitle);

It now no longer triggers a NullPointer and works!

For some reason though, NiceEditText editItem = (NiceEditText) findViewById(R.id.editItem); works without having to be called on the activity.

Chronicle
  • 1,565
  • 3
  • 22
  • 28