我一辈子都无法弄清楚为什么我会收到NullPointerException。

当用户单击特定图像时,应该弹出一个对话框并显示该图像的较大版本:

private OnClickListener coverListener = new OnClickListener()
{
 public void onClick(View v)
 {
  showDialog(DIALOG_COVER);
 }
};


DIALOG_COVER设置为= 0。

关联的onCreateDialog如下所示:

protected Dialog onCreateDialog(int id) {
 Dialog dialog;
 switch(id)
 {
  case DIALOG_COVER:
   dialog = new Dialog(mContext);
   dialog.setContentView(R.layout.cover_dialog);
   dialog.setTitle(book.getTitle());
   ImageView coverLarge = (ImageView)findViewById(R.id.coverLarge);
   coverLarge.setImageBitmap(book.getCover());
      break;
  default:
      dialog = null;
 }
 return dialog;
}


作为参考,这是cover_dialog.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/coverDialog"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="10dp">
<ImageView android:id="@+id/coverLarge"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:scaleType="fitStart"
           /></LinearLayout>


现在,当单击上述图像时,应用程序立即崩溃,并通过LogCat引发以下错误:

06-08 13:29:17.727: ERROR/AndroidRuntime(2220): Uncaught handler: thread main exiting     due to uncaught exception
06-08 13:29:17.757: ERROR/AndroidRuntime(2220): java.lang.NullPointerException
06-08 13:29:17.757: ERROR/AndroidRuntime(2220):     at org.kylehughes.android.brarian.AndroidBrarian.onCreateDialog(AndroidBrarian.java:259)


有问题的行引用onCreateDialog内部的这一行:

coverLarge.setImageBitmap(book.getCover());


基本上,我不明白为什么CoverLarge在那时为null。任何帮助将非常感激。

最佳答案

关于什么:

/** snip **/
LayoutInflater factory = LayoutInflater.from(mContext);
View dialogView = factory.inflate(R.layout.cover_dialog,null);
ImageView coverLarge = (ImageView)dialogView.findViewById(R.id.coverLarge);
dialog = new Dialog(mContext);
dialog.setContentView(dialogView);
dialog.setTitle(book.getTitle());
coverLarge.setImageBitmap(book.getCover());
/** snip **/


只是从头开始写的。请检查语法

07-27 14:05