androidbitmapimageviewbitmapfactorystartactivityforresult

Loading Image bitmap from user picked image into imageview doesn't set image


A beginner here..

I'm setting a image into Image View that will be picked by user, But when I'm picking image the imageview doesn't get the image loaded.

M app is just opening the file chooser, I'm choosing the image and its just not loading the picked image in imageview.

<ImageView
    android:layout_marginRight="5dp"
    android:id="@+id/logoImageView"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:layout_gravity="center|end"
     />

in java..

ImageView logoimage=findViewById(R.id.logoImageView);

I have this onclick listener on my Imageview..

logoImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent fileChoosingIntent =new Intent(Intent.ACTION_OPEN_DOCUMENT);
                fileChoosingIntent.setType("image/*");
                startActivityForResult(fileChoosingIntent,10);
            }
        });

OnActivityResults method

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode==10){

            logoImage.setImageBitmap(BitmapFactory.decodeFile(data.getData().getPath()));
        }
    }

androdi studio is giving this warning "Method invocation 'getData' may produce 'NullPointerException'" on data.getData() method...

I also have tried glide

Glide.with(this).load(data.getData()).into(logoImage);

I'm getting same results, blank imageview.

Rest of code is confidential( Can't a beginner have secret code..? :p)

NOTE- Its not showing anything in logcat Thank you so much for your suppport... :-)


Solution

  • You've mistaken the codes in the onActivityResult method. The requestCode is the one that identifies your request.

    From the Activity source code:

    requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.

    resultCode The integer result code returned by the child activity through its setResult().

    You should use resultCode to make sure that your request was successful though.

    When it comes to the NullPointerException warning, you should always check if used nullable variable isn't in fact null before accessing its fields or methods.

    So your startActivityResult() method using Glide should look more like this:

    @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if(requestCode == 10) {
                if (resultCode == RESULT_OK && data != null) {
                   Glide.with(this).load(data.getData()).into(logoImage);
                } else {
                  // optional null data handling
                }
            }
        }