Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

修正 Android 對話方塊中 EditText 取值的空指標異常

編輯:關於 Android 程式設計

撰寫一個包含輸入欄位的對話方塊時,點擊按鈕去讀取 EditText 的內容,卻一直收到空指標異常,折騰了好一陣子才找到原因。

原本的程式碼是這樣寫的:

// 更新對話方塊
private void updateDialog(final String id) {
    TableLayout updatemsg = (TableLayout) getLayoutInflater()
            .inflate(R.layout.updatemsg, null);

    new AlertDialog.Builder(this)
        .setTitle("更新該條信息")
        .setView(updatemsg)
        .setPositiveButton("更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String musicN = ((EditText) findViewById(R.id.musicN))
                        .getText().toString();
                String singerN = ((EditText) findViewById(R.id.singerN))
                        .getText().toString();
                updateData(db, id, musicN, singerN);
            }
        })
        .setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { }
        })
        .create()
        .show();
}
對話方塊載入的 updatemsg.xml 內容如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView android:layout_width="100dip"
    android:layout_height="wrap_content"
    android:text="音樂名"
    android:textSize="30px"
    android:textColor="#ffffff" />
<EditText android:id="@+id/musicN"
    android:layout_width="100dip"
    android:layout_height="wrap_content" />
<TextView android:layout_width="100dip"
    android:layout_height="wrap_content"
    android:text="歌手"
    android:textSize="30px"
    android:textColor="#ffffff" />
<EditText android:id="@+id/singerN"
    android:layout_width="100dip"
    android:layout_height="wrap_content" />

問題根源

問題出在 findViewById 的呼叫對象上。

Activity 中的 findViewById() 是從 Activity 自己的內容視圖(setContentView 設定的那個版面)裡搜尋子 View,它並不知道對話方塊裡還掛了另一份 XML。既然在 Activity 的版面樹中找不到 R.id.musicN,回傳的自然就是 null,後續呼叫 getText() 便拋出空指標異常。

換句話說,我們 inflate 出來的 updatemsg 才是這些控制項真正的父容器,取值時就該以它為起點。

解法

把兩行改成透過 updatemsg 這個 View 去查找:

String musicN = ((EditText) updatemsg.findViewById(R.id.musicN))
        .getText().toString();
String singerN = ((EditText) updatemsg.findViewById(R.id.singerN))
        .getText().toString();
改寫後的完整版本:

private void updateDialog(final String id) {
    View updatemsg = getLayoutInflater().inflate(R.layout.updatemsg, null);

    new AlertDialog.Builder(this)
        .setTitle("更新該條信息")
        .setView(updatemsg)
        .setPositiveButton("更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String musicN = ((EditText) updatemsg.findViewById(R.id.musicN))
                        .getText().toString();
                String singerN = ((EditText) updatemsg.findViewById(R.id.singerN))
                        .getText().toString();
                updateData(db, id, musicN, singerN);
            }
        })
        .setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { }
        })
        .create()
        .show();
}
順帶一提,這裡我把 updatemsg 的型別從 TableLayout 改為 View。既然只用它來做 findViewById 的起點,宣告成 View 更貼近實際用途,也不易誤導。

延伸提醒

這個觀念在 Fragment 中同樣適用。Fragment 的版面是在 onCreateView() 裡 inflate 出來的,若在 Fragment 中直接呼叫 getView().findViewById() 或 Activity 的 findViewById() 去找 Fragment 版面內的元件,一樣會拿到 null。正確做法是先保存 inflate 出來的根 View,再以它為起點查找,或是等到 onViewCreated() 之後再操作。

一句話總結:findViewById 永遠從「你要找的那個 View 所屬的版面樹」開始搜尋,而不是從 Activity 開始。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved