Android 应用程序在更改时崩溃 activity

Android app crashes when changing activity

Android 开发新手,使用 Android Studio。我的应用程序的第一个 activity 是一个带有“开始”和“退出”按钮的简单主菜单。当我按下“开始”按钮时,应用程序应将我带到第二个 activity 名为“EncounterScreen”的页面。相反,应用程序崩溃了。 enter image description here。我正在尝试显示 class 玩家的玩家对象的当前健康状况。显然问题出在“TextView healthText=findViewById(R.id.healthText);”。这是错误:“尝试在空对象引用上调用虚拟方法 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()'”

public class EncounterScreen extends AppCompatActivity implements View.OnClickListener {
  Player player=new Player();
  TextView healthText=findViewById(R.id.healthText); 


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_encounter_screen);
    Player player=new Player();
    TextView healthText=findViewById(R.id.healthText);
    healthText.setText("Health "+player.getCurrentHP());

    Button attackButton=findViewById(R.id.attackBtn);
    Button drinkPotButton=findViewById(R.id.drinkPotBtn);
    Button runButton=findViewById(R.id.runBtn);
    attackButton.setOnClickListener(this);
    drinkPotButton.setOnClickListener(this);
    runButton.setOnClickListener(this);

}

@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.drinkPotBtn:
            player.drinkPotion(player);
            healthText.setText("Health "+player.getCurrentHP());
        break;
        }

    }
Player player=new Player();
  TextView healthText=findViewById(R.id.healthText); 

我认为问题出在上面一行。删除 =findViewById(R.id.healthText).

确保您尝试查找的 TextView ID 具有正确的 ID。您正在使用“R.id.healthText”

您 activity_ecounter_screen 中的 TextView 是否有不同的 ID?