Search code examples
androidandroid-fragmentsbitmapandroid-imageviewandroid-image

How to transfer bitmap image from Activity to Fragment


I have an a bitmap image in my Activity like this:

Bitmap image4 = BitmapFactory.decodeResource(getResources(), R.drawable.hello);
        image1.setImageBitmap(image4);

I'm trying to pass this image in fragment using this code:

  FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                Secondfrag yourFragment = new Secondfrag();
                Bundle b = new Bundle();
                b.putParcelable("BitmapImage",image4);

                yourFragment.setArguments(b);
                fragmentTransaction.add(R.id.frag, yourFragment, "FRAGMENT");
               fragmentTransaction.commit();

and trying to get this image in fragment like this:

Bundle b=this.getArguments();
        String page=b.getString("BitmapImage");

        image2.setImageURI(Uri.parse(page));

But there is no image display in my Fragment.How to resolve this issue?


Solution

  • Convert it into byte array

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
      byte[] byteArray = stream.toByteArray();
    
    Bundle b = new Bundle();
    b.putByteArray("image",byteArray);
    
    
      // your fragment code 
    fragment.setArguments(b);
    

    Get value from destination fragment

    byte[] byteArray = getArgument().getByteArrayExtra("image");
    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    

    Credit to https://stackoverflow.com/a/33797090/4316327