Why this is how it works:

public void onButtonClick (View v){ EditText el1 = (EditText)findViewById(R.id.Num1); EditText el2 = (EditText)findViewById(R.id.Num2); TextView resText = (TextView)findViewById(R.id.Result); int num1 = Integer.parseInt(el1.getText().toString()); int num2 = Integer.parseInt(el2.getText().toString()); int resSum = num1 + num2; resText.setText(Integer.toString(resSum)); } 

But no

 EditText el1 = (EditText)findViewById(R.id.Num1); EditText el2 = (EditText)findViewById(R.id.Num2); TextView resText = (TextView)findViewById(R.id.Result); int num1 = Integer.parseInt(el1.getText().toString()); int num2 = Integer.parseInt(el2.getText().toString()); public void onButtonClick (View v){ int resSum = num1 + num2; resText.setText(Integer.toString(resSum)); } 

Where did my brilliant plan go according to plan?

    2 answers 2

    The findViewById method searches for the View in the previously loaded layout. You must load it in the onCreate method. And this method, like any other, cannot be called until the class has been fully loaded into the JVM. When a class is loaded into the JVM, all the fields of this class are initialized. Just at the moment of initialization, the findViewById method is called in this case and tries to find a view in the not yet loaded markup, which, as expected, fails.

    Those. here it is in the order of execution of the code.

    • Thank you so much for the explanation - Mr.Reyzon pm

    Edited here, so that errors are possible, but the direction is about

    Try this

     private EditText el1; private EditText el2; private TextView resText; private int num1; private int num2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); el1 = (EditText)findViewById(R.id.Num1); el2 = (EditText)findViewById(R.id.Num2); resText = (TextView)findViewById(R.id.Result); public void onButtonClick (View v){ num1 = Integer.parseInt(el1.getText().toString()); num2 = Integer.parseInt(el2.getText().toString()); int resSum = num1 + num2; resText.setText(Integer.toString(resSum)); } } 
    • Everything works, thank you - Mr.Reyzon