如何解决更改活动时,Android应用程序崩溃
使用Android Studio开发Android的新手。我的应用程序的第一个活动是带有“开始”和“退出”按钮的简单主菜单。当我按下“开始”按钮时,应用程序应带我进入名为“ EncounterScreen”的第二个活动。而是,应用程序崩溃了。 enter image description here。我正在尝试显示Player类的Player对象的当前运行状况。显然问题出在“ 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;
}
}
解决方法
确保您要查找的TextView ID具有正确的ID。您正在使用“ R.id.healthText”
您的activity_ecounter_screen中的TextView是否具有其他ID?
,Player player=new Player();
TextView healthText=findViewById(R.id.healthText);
我认为问题在于上述内容。删除 = findViewById(R.id.healthText)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。