標籤:android對話方塊擷取不到值 android對話方塊獲值null 指標 android對話方塊的按鈕事件
寫的一個Android對話方塊,點擊按鈕擷取EditText裡面的值,這裡一直報null 指標異常,研究了很長時間終於解決了。
異常如下:
我原來的代碼:
//更新對話方塊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(){@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubString 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();}
對話方塊中引入了另一個xml設定檔updatemsg.xml:
<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TableRow> <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" /> </TableRow> <TableRow> <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" /> </TableRow></TableLayout>,
問題解決
出錯原因就是這個引入的xml
在通過findViewById找EditText的時候,它是從原來的布局檔案裡面找的,而不是對話方塊的布局檔案,所以當然要報null 指標異常
怎樣讓才能找到對話方塊的布局檔案呢?
把那兩句改成;
String musicN = ((EditText)updatemsg.findViewById(R.id.musicN)).getText().toString();
String singerN = ((EditText)updatemsg.findViewById(R.id.singerN)).getText().toString();