Android 访问警报对话框中编辑文本的getText()时的空指针
我正在尝试创建一个警报对话框,其中包含一个文本字段和一个按钮。 我面临的问题是,Android 访问警报对话框中编辑文本的getText()时的空指针,android,Android,我正在尝试创建一个警报对话框,其中包含一个文本字段和一个按钮。 我面临的问题是,String str=ets.toString()在editText对象上,它抛出java.lang.NullPointerException。 我错过什么了吗 Java代码: private void newDialog1(Context ct) { final View v = getLayoutInflater().inflate(R.layout.layout, null);
String str=ets.toString()
在editText对象上,它抛出java.lang.NullPointerException。
我错过什么了吗
Java代码:
private void newDialog1(Context ct) {
final View v = getLayoutInflater().inflate(R.layout.layout, null);
AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);
ad.setView(v);
setContentView(R.layout.layout);
ad.setTitle("Enter Password");
ad.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d(TAG, "Yes clicked");
EditText et = (EditText) (v.findViewById(R.id.editText));
if (et == null)
Log.e(TAG, "Null");
else {
Editable ets = et.getText();
String str=ets.toString();
Toast.makeText(MainActivity.this,str, Toast.LENGTH_SHORT).show();
}
}
}).create().show();
}`
布局xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/adDialog">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_height="wrap_content"
/>
删除setContentView(R.layout.layout)
删除setContentView(R.layout.layout)
并发布整个stacktraceAlso,您只需在一行`String str=et.getText().toString()中完成;