Home > database >  How to solve Photopicker error in android Studio?
How to solve Photopicker error in android Studio?

Time:01-17

I have the following code , im receiving an error :

enter image description here

package com.example.photopicker;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button addimage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addimage=findViewById(R.id.button_pick_photo);
       addimage.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
            // Registers a photo picker activity launcher in single-select mode.
               ActivityResultLauncher<PickVisualMediaRequest> pickMedia =
                       registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
                           // Callback is invoked after the user selects a media item or closes the
                           // photo picker.
                           if (uri != null) {
                               Log.d("PhotoPicker", "Selected URI: "   uri);
                           } else {
                               Log.d("PhotoPicker", "No media selected");
                           }
                       });

            // Include only one of the following calls to launch(), depending on the types
            // of media that you want to allow the user to choose from.

             // Launch the photo picker and allow the user to choose images and videos.
               pickMedia.launch(new PickVisualMediaRequest.Builder()
                       **.setMediaType(new  ActivityResultContracts.PickVisualMedia.ImageAndVideo())**
                       .build());
           }
       });
    }
}

This code i got it from the Android developer Website : https://developer.android.com/training/data-storage/shared/photopicker

but Doesnt seem to work , and im not able to find any online solution.

CodePudding user response:

  • The easy way - launch the Gallery with an intent, and get the media URI in onActivityResult.
  • The hard way - fetch thumbnail and full-size URIs from the MediaStore ContentProvider.

Make sure to enable access to the external storage first before using the camera (Note: The permissions model has changed starting in Marshmallow. If your targetSdkVersion >= 23 and you are running on a Marshmallow (or later) device, you may need to enable runtime permissions. You should also read more about the runtime permissions changes):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
    <!- ... -->

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!- ... -->
</manifest>

Easy way is to use an intent to launch the gallery:

// PICK_PHOTO_CODE is a constant integer
public final static int PICK_PHOTO_CODE = 100;

// Trigger gallery selection for a photo
public void onPickPhoto(View view) {
    // Create intent for picking a photo from the gallery
    Intent intent = new Intent(Intent.ACTION_PICK,
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    
    // If you call startActivityForResult() using an intent that no app can handle, your app will crash.
    // So as long as the result is not null, it's safe to use the intent.
    if (intent.resolveActivity(getPackageManager()) != null) {
       // Bring up gallery to select a photo
       startActivityForResult(intent, PICK_PHOTO_CODE);
    }
}

public Bitmap loadFromUri(Uri photoUri) {
    Bitmap image = null;
    try {
        // check version of Android on device
        if(Build.VERSION.SDK_INT > 27){
            // on newer versions of Android, use the new decodeBitmap method
            ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), photoUri);
            image = ImageDecoder.decodeBitmap(source);
        } else {
            // support older versions of Android by using getBitmap
            image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((data != null) && requestCode == PICK_PHOTO_CODE) {
        Uri photoUri = data.getData();

        // Load the image located at photoUri into selectedImage
        Bitmap selectedImage = loadFromUri(photoUri);

        // Load the selected image into a preview
        ImageView ivPreview = (ImageView) findViewById(R.id.ivPreview);
        ivPreview.setImageBitmap(selectedImage);
    }
}

CodePudding user response:

Try replacing:

new ActivityResultContracts.PickVisualMedia.ImageAndVideo()

with:

ActivityResultContracts.PickVisualMedia.Companion.getImageAndVideo()

ImageAndVideo is a Kotlin object — it is not a class that you instantiate yourself. However, the source code lacks the @JvmField annotation, so I think that just referring to ActivityResultContracts.PickVisualMedia.ImageAndVideo will fail, as outlined in the docs.

  • Related