how get image from gallery in fragment(jetpack navigation component)

Viewed 2158

I use Navigation component jetpak and in fragment need to get image from gallery. i use this code:

 ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
                new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            Constants.toast("return!");
            imageFile = new File(getRealPathFromURI(uri));
            binding.menuFragmentCircularProfileImageview.setImageURI(uri);
        }
    });

and after fragment attached call mGetContent

binding.menuFragmentCircularProfileImageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               mGetContent.launch("image/*");
           //     fromGallery();
            }
        });

So far everything is fine and the gallery opens well. BUT...

But the selected image does not return. The app is actually closed. Where did I do wrong? Or is there another solution?

UPDATED...

this is my fragment:

public class MenuFragment extends Fragment implements LogoutDialog.Listener {
    private FragmentMenuBinding binding;
    private NavController navController = null;
    private UserData userData;
    private File imageFile;
    private final androidx.activity.result.ActivityResultLauncher<String> getContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
            new ActivityResultCallback<Uri>() {
                @Override
                public void onActivityResult(Uri uri) {
                    Bitmap bitmap = null;
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(requireActivity().getContentResolver(), uri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    binding.menuFragmentCircularProfileImageview.setImageBitmap(bitmap);
                }
            });
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        navController = Navigation.findNavController(requireActivity(), R.id.main_activity_nav_host_fragment);
        binding = DataBindingUtil.inflate(inflater , R.layout.fragment_menu, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        assert getArguments() != null;
        userData=MenuFragmentArgs.fromBundle(getArguments()).getUserdata();
        operation();
    }


    private void operation(){
        binding.menuFragmentCircularProfileImageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             getContent.launch("image/*");
            }
        });
    }
}
3 Answers

Try using below code:

     private ActivityResultLauncher startForResultFromGallery = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
             @Override
             public void onActivityResult(ActivityResult result) {
                 if (result.getResultCode() == Activity.RESULT_OK){
                     try {
                         if (result.getData() != null){
                             Uri selectedImageUri = result.getData().getData();
                            Bitmap bitmap = BitmapFactory.decodeStream(getBaseContext().getContentResolver().openInputStream(selectedImageUri));
                            // set bitmap to image view here........
          binding.menuFragmentCircularProfileImageview.setImageBitmap(bitmap)
                         }
                     }catch (Exception exception){
                         Log.d("TAG",""+exception.getLocalizedMessage());
                     }
                 }
             }
         });

And call above inside your button click like :

    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startForResultFromGallery.launch(intent);

You can use this inside your onActivityResult to get the file

InputStream inputStream = requireActivity().contentResolver().openInputStream(uri)
String fileType = MimeTypeMap.getSingleton().getExtensionFromMimeType(requireContext().contentResolver().getType(uri))
imageFile = File.createTempFile(UUID.randomUUID().toString(), "." + fileType)
inputStream.copyStreamToFile(file)

I have ported this code from Kotlin let me know if some syntax is wrong.

I believe you have android:noHistory="true" in your AndroidManifest.xml, please remove it, and you should receive the result. I believe the problem has no relation with Jetpack navigation.

Related