添加OnclickListener后,我的Android应用程序崩溃

I tried to build an easy Android App using Java and, obviously, Android studio. After adding an OnClickListener the app keeps crashing on the emulator. public class MainActivity extends AppCompatActivity { EditText first = findViewById(R.id.firstInput); EditText second = findViewById(R.id.secondInput); EditText result = findViewById(R.id.result); private Button add; private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { clicked(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); add = new Button(this); add.setOnClickListener(onClickListener); }; void clicked(){ int i = Integer.parseInt(first.getText().toString()); int z = Integer.parseInt(second.getText().toString()); int r = i + z; result.setText(r); } };


Wrong location of object declaration It should be below the setContentView EditText first = findViewById(R.id.firstInput); EditText second = findViewById(R.id.secondInput); EditText result = findViewById(R.id.result); Button haven't added to the layout add = new Button(this); addContentView(add, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); Note: This is impractical, you should have added this on your layout xml unless you wanted to create dynamic layout Warning issue of setting a text by integer From: result.setText(r); To: result.setText(String.valueOf(r));