views:

453

answers:

2

I am trying to get the value of a EditText in a dialog box. A the "*"'ed line in the following code, the safeNameEditText is null; i am assuming because the 'findVeiwById' is searching on the context of the 'AlertDialog.OnClickListener'; How can I get/change the context of that 'findViewById' call?

 protected Dialog onCreateDialog(int id) {
  AlertDialog.Builder builder = new AlertDialog.Builder(this);

  switch(id){
   case DIALOG_NEW_SAFE:
    builder.setTitle(R.string.news_safe);
    builder.setIcon(android.R.drawable.ic_menu_add);

    LayoutInflater factory = LayoutInflater.from(this); 
    View newSafeView = factory.inflate(R.layout.newsafe, null);

    builder.setView(newSafeView);
    builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener(){
     public void onClick(DialogInterface dialog, int which) {
 *     EditText safeNameEditText = (EditText) findViewById(R.id.new_safe_name);
      String safeName = safeNameEditText.getText().toString();
      Log.i(LOG, safeName);
      setSafeDao(safeName);
     }     
    });

    builder.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener(){
     public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
     } 
    });
    return(builder.create());
   default:
    return(null);
  }
 }
A: 

Not really the answer to your question but this will help you achieve what you are trying to do...

final EditText safeNameEditText = (EditText) findViewById(R.id.new_safe_name);
builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
    String safeName = safeNameEditText.getText().toString();
    Log.i(LOG, safeName);
    setSafeDao(safeName);
}     
});
Prashast
thanks, i thought that may actually get get the EditText, but safeNameEditText is still null.no clue why... do i have to do something special to find a View if it is part of a dialog?
wuntee
findViewById uses the view that is currently set for the Activity. If the id is not present in that view then it will return null.
Prashast
+2  A: 

I think you need to reference the view, since the dialog box does not see that edittext field:

EditText safeNameEditText = (EditText) newSafeView.findViewById(R.id.new_safe_name);

joet3ch