在AlertDialog中从用户检索信息

时间:2013-02-02 14:42:33

标签: java android input android-edittext alertdialog

我一直在简化和简化,试图从AlertDialog中的EditText获取一串文本而没有成功

private void showAddSectorDlg() {
   if (BuildConfig.DEBUG) {
           Log.i(Constants.TAG_ACTSECTORS, "showAddSectorDialog() called.");
   }
   LayoutInflater inflater = getLayoutInflater();
   new AlertDialog.Builder(ActSectors.this)
   .setTitle(R.string.menu_new_sector)
   .setMessage(R.string.dlg_sect_add_msg)
   .setView(inflater.inflate(R.layout.dlg_sector_add, null))
   .setPositiveButton(R.string.dlg_save,
           new DialogInterface.OnClickListener() {
               public void onClick(
                       DialogInterface dialog,
                       int whichButton) {
                    EditText mNewSectorName = (EditText) findViewById(R.id.dlg_edt_nsector);   
                            //NullPointerException happens here:
                    String val = mNewSectorName.getText().toString();
                       if (BuildConfig.DEBUG) {
                        Log.i(Constants.TAG_ACTSECTORS, "New Sector Name: "+val);
                       }
                       grabVal(val);
                       dialog.dismiss();
                   }
           })
   .setNegativeButton(R.string.dlg_cancel,
           new DialogInterface.OnClickListener() {
               public void onClick(
                       DialogInterface dialog,
                       int whichButton) {
               }
           }).create().show();
   }

   private void grabVal(String newSector){
   mNSN = newSector;
   callCtlr(Constants.R_DB_ADDSECT);
   }

如果有人能解释我的错误在哪里,我将不胜感激......谢谢!

1 个答案:

答案 0 :(得分:1)

更改代码,以便从AlertDialog的EditText中获取值:

 LayoutInflater inflater = getLayoutInflater();
  View view=inflater.inflate(R.layout.dlg_sector_add,null);
   new AlertDialog.Builder(ActSectors.this)
   .setTitle(R.string.menu_new_sector)
   .setMessage(R.string.dlg_sect_add_msg)
   .setView(view)
   //... your code here

现在使用view从AlertDialog访问EditText:

EditText mNewSectorName = (EditText)view.findViewById(R.id.dlg_edt_nsector);