setImageResource导致NULL指针异常

时间:2013-12-09 05:22:21

标签: android nullpointerexception imageview

我有一个对话框。有一个Imageview。在以编程方式设置图像时,我得到NullPointerException。这是我的对话框代码

      LayoutInflater inflater = Tutorial7.this.getLayoutInflater();
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                //Yes button clicked
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
            }
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(Tutorial7.this);
    builder.setView(inflater.inflate(R.layout.dialogview, null));
    myimage = (ScaleImageView)findViewById(R.id.dialogboximage);
    String mypath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/target.jpg";
    File mydir = new File(mypath);
    try
    {
        if(mydir.exists())
            System.out.println("True");
        else
            System.out.println("False");
    }
    finally{
    System.out.println("The file i am trying to decode:-"+Environment.getExternalStorageDirectory().getAbsolutePath() + "/target.jpg");
    }

    /* I am getting error in this line*/myimage.setImageResource(R.drawable.button_chair_selected);
    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
        .setNegativeButton("No", dialogClickListener).show();

dialogbox.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" 
 android:weightSum="2">

 <com.myapp.myarapp.ScaleImageView
    android:id="@+id/dialogboximage"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    />

</LinearLayout>

1 个答案:

答案 0 :(得分:3)

更改此

 myimage = (ScaleImageView)findViewById(R.id.dialogboximage);

 View v= inflater.inflate(R.layout.dialogview, null);
 builder.setView(v);
 myimage = (ScaleImageView)v.findViewById(R.id.dialogboximage);
相关问题