Android应用点击按钮崩溃求助:NullPointerException报错
Hey there, let's get this crash sorted out! The root cause of your NullPointerException is pretty straightforward:
Why the Crash Happens
You're only initializing the t1 and t2 TextView references inside the goal1() and goal2() methods. If a user taps the winner button without first tapping either goal button, t1 and t2 will still be null when you try to call getText() on them in the winner() method—hence the empty object reference error.
The Fix
The best practice is to initialize your View references once when the Activity is created, inside the onCreate() method. This way, the TextView objects are ready to use no matter which button the user taps first.
Here's the updated MainActivity code:
public class MainActivity extends AppCompatActivity { public static final String EXTRA_MESSAGE = "com.example.amarjeet.goal"; TextView t1,t2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize TextViews here once when the Activity starts t1 = findViewById(R.id.t1); t2 = findViewById(R.id.t2); } public void goal1(View view){ // No need to call findViewById here anymore int currentScore = Integer.parseInt(t1.getText().toString()); t1.setText(String.valueOf(currentScore + 1)); } public void goal2(View view){ // No need to call findViewById here anymore int currentScore = Integer.parseInt(t2.getText().toString()); t2.setText(String.valueOf(currentScore + 1)); } public void winner(View view){ Intent intent = new Intent(this, Winner.class); String msg; // Now t1 and t2 are guaranteed to be non-null here int score1 = Integer.parseInt(t1.getText().toString()); int score2 = Integer.parseInt(t2.getText().toString()); if(score2 > score1){ msg = "Winner is Team B"; } else if(score1 > score2) { msg = "Winner is Team A"; } else { msg = "Match is Draw"; } intent.putExtra(EXTRA_MESSAGE, msg); startActivity(intent); } }
Extra Tip to Avoid Another Crash
Make sure your TextViews in activity_main.xml have an initial numeric value (like android:text="0"). If they're empty or have non-numeric text, Integer.parseInt() will throw a NumberFormatException when you try to parse the text.
内容的提问来源于stack exchange,提问作者Amarjeet

