【问题标题】:Android app crashes when changing activity [duplicate]更改活动时Android应用程序崩溃[重复]
【发布时间】:2020-08-21 17:33:19
【问题描述】:

Android 开发新手,使用 Android Studio。我的应用程序的第一个活动是一个带有“开始”和“退出”按钮的简单主菜单。当我按下“开始”按钮时,该应用程序应将我带到名为“EncounterScreen”的第二个活动。相反,应用程序崩溃了。 enter image description here。我正在尝试显示 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;
        }

    }

【问题讨论】:

  • 请发布崩溃错误信息
  • 你不能在 onCreate 和 setContentView(R.layout.activity_encounter_screen); 之前初始化一个 TextView您现在在构造函数中执行此操作。将它放在 setContentView 之后的 onCreate 中

标签: java android nullpointerexception


【解决方案1】:

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

activity_ecounter_screen 中的 TextView 是否有不同的 id?

【讨论】:

  • id 是正确的,我检查了。
【解决方案2】:
Player player=new Player();
  TextView healthText=findViewById(R.id.healthText); 

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

【讨论】:

  • 删除该部分有效。对播放对象做了同样的事情。现在它切换活动而不会崩溃。但是现在当我点击应该增加生命值的“喝药水”按钮并在屏幕上显示变化时,它崩溃了。现在它说: java.lang.NullPointerException: Attempt to call virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' 在 com.example.adventuregamealpha.EncounterScreen.onClick(EncounterScreen.爪哇:42)。它指的是这一行:healthText.setText("Health"+player.getCurrentHP());
  • 删除 findViewById 只会创建一个新错误,这不是一个可接受的答案
  • 我相信在调用onCreate方法之前从语句中删除findViewById不会产生新的BUG。 @JacobKaddoura。
  • 删除它不是答案,也许移动它可能是一个解决方案,但删除它会产生问题,因为 OP 希望稍后在视图引用上调用 setText()。 @CharanKumar
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 2018-06-26
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多