从图库中选择图像后出现空白屏幕

问题描述

我正在尝试将图像放入 ImageView,但是每当我单击图库上的图片时,该应用程序都会显示一个空白屏幕并关闭。 这个 ImageView 在一个片段中

公共视图 onCreateView(LayoutInflater inflater,ViewGroup 容器,捆绑savedInstanceState) { 查看 v = inflater.inflate(R.layout.fragment_auction_add,container,false);

    auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);

    auction_add_imageViewButton.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageSelectAction(v);
        }
    });


    dateTimeAction(v);


    return v;
}

private void imageSelectAction(View v) {
    auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
    auction_add_image = v.findViewById(R.id.auction_add_imageView);

    choosePicture();

}

private void choosePicture() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Picture"),SELECT_PICTURE);
}

@Override
public void onActivityResult(int requestCode,int resultCode,@Nullable Intent data) {
    super.onActivityResult(requestCode,resultCode,data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            if (data != null && data.getData() != null) {
                Uri selectedImageUri = data.getData();

                auction_add_image.setimageURI(selectedImageUri);
            }
        }
    }
}

初始声明

public class auction_add extends Fragment {


    private static final int SELECT_PICTURE = 10;
    private static final int PERMISSION_CODE = 11;
    ImageButton auction_add_imageViewButton;


    //References to all Auction Add Page EditText
    EditText auction_add_itemNameTxt;
    EditText auction_add_descriptionTxt;
    EditText auction_add_initialPriceTxt;
    EditText auction_add_startTimeTxt;
    EditText auction_add_endTimeTxt;

    //Reference to ImageView
    private ImageView auction_add_image;

    final Calendar myCalendar = Calendar.getInstance();

感谢您的帮助!

编辑:

以下是Android Studio运行选项卡上的错误

W/System: A resource Failed to call close. 
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.projectcrest,PID: 5618
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,request=242868079,result=-1,data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setimageURI(android.net.Uri)' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setimageURI(android.net.Uri)' on a null object reference
        at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
        at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
        at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
        at androidx.activity.result.ActivityResultRegistry.dodispatch(ActivityResultRegistry.java:377)
        at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
        at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
        at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
        at android.app.Activity.dispatchActivityResult(Activity.java:8310)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 5618 SIG: 9

解决方法

通过查看异常,似乎由于 NPE(空指针异常),应用程序在 #onActivityResult 行的 auction_add_image.setImageURI(selectedImageUri); 函数中崩溃。这种预期/崩溃是由于 auction_add_image 对象具有空值而不是 ImageView 引起的。

仔细查看您的代码后,我认为问题是由以下代码引起的:

    auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);

    auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageSelectAction(v);
        }
    });

请注意,在 #onClick 函数中,您正在传递将在其上执行 #findViewById 操作的视图 v。此处传递的视图 v 指的是 auction_add_imageViewButton 而不是您在上面捕获的 v

我建议修改如下代码(只需重命名#onClick 函数中的 v 变量):

    auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);

    auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View buttonView) {
            imageSelectAction(v);
        }
    });

这样可以避免变量名冲突并解决错误。

此外,如果这不能解决您的问题,请检查 #findViewById 是否返回 ImageView 而不是 null。如果提供给 #findViewById 的 Id 不存在于屏幕上或正在执行的视图的子视图中(#findViewById),则 #findViewById 将返回空值。

此外,请检查您是否在代码的任何位置为 auction_add_image 分配了空值。