2011-12-14 66 views
0

我在對話框中有一個EditText,用戶將在其中輸入一個新類別。但是,當我嘗試訪問EditText中的值 - 我得到了空指針異常。對話框 - 編輯文本中訪問值的問題

執行過程。

有一個類別微調框 當用戶從微調框中選擇新的類別時,會向用戶顯示一個對話框。

代碼對話框如下:

//check if spCategories == new category 
    if(arg0.getSelectedItem().toString().equals("New Category")) { 
    //Show dialog box for adding new category 
    Dialog dialog = new Dialog(AddTransaction.this); 
    dialog.setContentView(R.layout.newcategory); 
    dialog.setTitle("New Category"); 
    dialog.setCancelable(true); 
    dialog.show(); 

    Button btnAddCat = (Button) dialog.findViewById(R.id.btnAddCategory); 
    final EditText etCategory = (EditText) findViewById(R.id.etNewCategory); 

    btnAddCat.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
     **Log.v("EXT", "Category type is : " + etCategory.getText());** 
    } 
         } 
    }); 

我得到空指針異常的加粗線時

任何想法。對話框的佈局在XML文件中定義。

回答

1

行:

final EditText etCategory = (EditText) findViewById(R.id.etNewCategory); 

是錯誤的,你必須改變它: 「對話框」

final EditText etCategory = (EditText) dialog.findViewById(R.id.etNewCategory); 

無您正在活動佈局而不是對話框中搜索該視圖。

+0

非常好 - 非常感謝 - 奇怪的是我用dialog.find聲明瞭正確的按鈕方式...... - 但沒有想到編輯文本 – 2011-12-15 01:48:59