2012-11-27 174 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

這是最好的方式來做到這一點,謝謝 –