9

我有以下创建警报对话框的代码,并向其中添加了两个编辑文本,但是一旦我运行应用程序,EditText 中的值将不会被检索,并且我的应用程序因 NullPointerException 而崩溃:

代码是:

AlertDialog.Builder alert = new AlertDialog.Builder(this);
        LayoutInflater inflater=this.getLayoutInflater();
        final EditText usernameInput=(EditText)findViewById(R.id.dialogusername);
        final EditText passwordInput=(EditText)findViewById(R.id.dialogpassword);   
        alert.setView(inflater.inflate(R.layout.dialog,null));
        alert.setTitle("Enter Password");
        alert.setMessage("Enter password to remove the app:");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            //provide user with caution before uninstalling
            //also here should be added a AsyncTask that going to read the password and once its checked the password is correct the app will be removed
            value1=usernameInput.getText().toString();
            value2=passwordInput.getText().toString();
            if(value1.equals(null)&&value2.equals(null))
            {Toast.makeText(context, "Enter username and password", Toast.LENGTH_SHORT).show();}
         }
        });
        });
        alert.show();
4

3 回答 3

25

感谢大家为回答我的问题所做的贡献,我想我已经找到了我上面发布的问题的解决方案:

AlertDialog.Builder alert = new AlertDialog.Builder(MyFeedActivity.this);
        LayoutInflater inflater=MyFeedActivity.this.getLayoutInflater();
        //this is what I did to added the layout to the alert dialog
        View layout=inflater.inflate(R.layout.dialog,null);       
        alert.setView(layout);
        final EditText usernameInput=(EditText)layout.findViewById(R.id.dialogusername);
        final EditText passwordInput=(EditText)layout.findViewById(R.id.dialogpassword);

而且我认为问题在于我无法在警报对话框中获取 EidtText,但是通过上面的代码执行此操作,一切对我来说都很好。

于 2012-11-28T15:11:22.703 回答
14

用这个:

final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    final EditText input = new EditText(this);
    input.setHint("hint");
    alertDialog.setTitle("title");
    alertDialog.setMessage(message);
    alertDialog.setView(input);
于 2012-11-27T12:20:22.280 回答
1

尝试像这样编辑

final EditText usernameInput=(EditText)this.findViewById(R.id.dialogusername);
final EditText passwordInput=(EditText)this.findViewById(R.id.dialogpassword);

或者

final EditText usernameInput=(EditText)alert.findViewById(R.id.dialogusername);
final EditText passwordInput=(EditText)alert.findViewById(R.id.dialogpassword);
于 2012-11-27T12:18:32.980 回答