Home > Software design >  Why I'm getting null exceptionj when I run the same function for the second time?
Why I'm getting null exceptionj when I run the same function for the second time?

Time:02-23

I have a button over which I call the fucntion click WHen I click the button 2nd time, app crashes. It is because I call setEdit on null object. Is there some other way to solve the problem than the second variation given below with if(!=null) ? Is there an explanation why I'm getting this null exception ?

public void click(View view) {

        EditText editText = (EditText)findViewById(R.id.simpleEditText);


    if (editText != null)  { editText.setId(202); }

}

But his works fine:

public void click(View view) {

        EditText editText = (EditText)findViewById(R.id.simpleEditText);


    if (editText != null)  { editText.setId(202); }

}

CodePudding user response:

THis is from the conversation, showing him how to get views and store them.

public class MyActivity extends Activity {

    private TextView text1;

    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.mylayout);
        text1 = findViewById(R.id.text);
    }

    private void someFunc() {
        text1.setText("Hey I used the variable");
    }
}
  • Related