我尝试了很多事情,但是我的应用程序不断崩溃。
我尝试调试,然后在运行应用程序时返回此错误。
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个小时。
答案 0 :(得分:2)
您只能在创建对话框之后(在onClick内部)调用dialog.findViewById
。创建活动时,它没有内容,因此您无法找到其视图。例如,正确获取dialogButton
因此,当您尝试从不存在的视图中获取文本时,它将引发异常