Android Dialog InvocationTargetException

时间:2011-06-16 12:41:47

标签: android exception dialog

我想要一个对话框,用户可以输入用户名和密码来注册他的应用程序 对话框显示但如果我输入任何数据并单击我的确认按钮,异常即将出现=( 有谁知道为什么我得到这个例外?

    Context mContext = getApplicationContext();
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.dialog_register_app, (ViewGroup) findViewById(R.id.layout_root));

    //Start building dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(getString(R.string.dialog_register_app_title));
    builder.setView(layout);
    builder.setCancelable(false);
    builder.setPositiveButton(getString(R.string.dialog_register_confirm_button_text), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //Auslesen der EditText
            EditText oUsername = (EditText) findViewById(R.id.edit_username);
            String strUsername = oUsername.getText().toString(); // This is line where exception is calling
            //Do something with strUsername
        }
   });
   AlertDialog alert = builder.create();
   alert.show();
...
...
...

2 个答案:

答案 0 :(得分:1)

这应该可以使它工作,因为应用程序需要知道它需要从哪个布局(View)中选择带有id edit_username ....的edittext,因此应该在您创建的视图上调用findViewById方法,而不是查看当前活动...希望有所帮助

EditText oUsername = (EditText) layout.findViewById(R.id.edit_username);
            String strUsername = oUsername.getText().toString(); // This is line where exception is calling
...

答案 1 :(得分:0)

如果此代码发生在Activity中,那么findViewById(...)可能无法按预期方式运行。您的活动布局中是否有EditText视图?

而是试试这个:

EditText oUsername = (EditText) layout.findViewById(R.id.edit_username);
String strUsername = oUsername.getText().toString();