2012-11-27 127 views
9

我有下面的代码,创造警告对话框,我添加了两个编辑短信给它,但一旦我运行应用程序中的EditText内的值不会retrived我与NullPointerException异常应用程序崩溃:将EditText添加到警报对话框。

的代码是:

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(); 
+0

你调用了错误的findViewById。调用alert.findViewByID – Yahor10

+0

感谢Yahor10,但我试图按照你的方式做,并不断收到错误,因为没有函数调用alert.findViewById();我唯一得到的是this.findViewById()这也没有工作..但任何我如何张贴解决方案,我用于解决这个问题下面.. –

回答

22

谢谢你们在回答我的问题你的贡献,我觉得我得到了我发布上述这些问题的解决方案是:

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,但通过上述代码实现它,每件事情都可以正常工作。

1

尝试编辑这样

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

OR

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

使用本:

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); 
+0

这是最好的方式来做到这一点,谢谢 –