2013-02-02 66 views
0

我一直在简化和努力得到的文本字符串从一个EditText在AlertDialog没有成功检索信息从用户AlertDialog

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

改变你的代码,以从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 

而现在使用视图从AlertDialog访问的EditText:

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

谢谢...那谁干的,我不得不声明最终的视图,但现在它返回正确的值! – Quasaur

+0

@Quasaur:最受欢迎的朋友。并且不需要将视图声明为final,只需在Activity的onCreate方法之前将其声明为类级别字段即可 –