【发布时间】:2020-01-24 14:45:41
【问题描述】:
我尝试了很多方法,但我的应用程序不断崩溃。
我尝试调试它,当我运行应用程序时返回此错误。
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.text.Editable android.widget.EditText.getText()”
package com.zybooks.pigdice;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
final Context context = this;
//private EditText playerName;
private String name;
private int target_score_display;
//public TextView player_name;
private EditText targetScore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//player_name = findViewById(R.id.player_name);
targetScore = dialog.findViewById(R.id.enter_target_score);
//playerName = findViewById(R.id.enter_player_name);
Button start_game = findViewById(R.id.start_game);
start_game.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialogbox);
dialog.setTitle("Title...");
Button dialogButton = dialog.findViewById(R.id.start_game_dialog);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
String value = targetScore.getText().toString();
target_score_display = Integer.parseInt(targetScore.getText().toString());
Intent intent = new Intent(getApplicationContext(),Gameplay.class);
intent.putExtra("TARGET_SCORE",target_score_display);
Bundle bundle = new Bundle();
bundle.putString("TARGET_SCORE",value);
intent.putExtras(bundle);
startActivity(intent);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
});
dialog.show();
}
});
}
}
试图将对话框中的输入传递给下一个活动。已经为此苦苦挣扎了 3 个多小时。
【问题讨论】:
-
使用
targetScore = findViewById(R.id.enter_target_score);代替:targetScore = dialog.findViewById(R.id.enter_target_score); -
targetScore = dialog.findViewById(R.id.enter_target_score);只需 findViewById
-
您显示的内容不应该编译(对话框在错误的范围内使用)。但是您需要查看完整的堆栈跟踪,而不仅仅是异常消息
标签: java android nullpointerexception android-edittext