2013-02-02 64 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方法之前將其聲明爲類級別字段即可 –