我希望我的应用在第一个AlertDialog中采用用户名形式的用户并将其发布在第二个AlertDialog中,但是当我添加以下代码行时,我的应用崩溃:txt.setText(edt.getText()。toString());。应该将textview更改为在第一个AlertDialog上给定的edittext值。
这是错误。
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.myapplication.MainActivity.Alert01(MainActivity.java:73)
at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:62)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
EditText edt;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
edt = (EditText) findViewById(R.id.edit_username);
txt = (TextView) findViewById(R.id.text02);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
Alert();
}
public void Alert () {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyDialogTheme);
View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog0, null);
builder.setMessage("Welcome ! ");
builder.setView(v);
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Alert01();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void Alert01 (){
txt.setText(edt.getText().toString());
AlertDialog.Builder builder01 = new AlertDialog.Builder(MainActivity.this,R.style.MyDialogTheme);
View v01 = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog1,null);
builder01.setView(v01);
builder01.setTitle("Congratulations ! ");
AlertDialog alert = builder01.create();
alert.show();
}
}
最佳答案
扩大布局后,在Alert()方法内移动此行
edt = (EditText) v.findViewById(R.id.edit_username);
同时修改Alert01()方法
AlertDialog.Builder builder01 = new AlertDialog.Builder(MainActivity.this,R.style.MyDialogTheme);
View v01 = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog1,null);
builder01.setView(v01);
txt = (TextView) v01.findViewById(R.id.text02);
txt.setText(edt.getText().toString());
关于java - 尝试调用虚拟方法(EditText),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57441548/