0

I have developed an app that allows the following: 1. Load image from gallery and view using ImageView. 2. Save image from ImageView into gallery. 3. An alert dialog box pops out which opens into another layout when clicked 'yes'.

I would like to pass the image bitmap from the first activity to the second activity. I have followed few example but the image is not being passed. My coding are as follows.

LoadImage.java:

public class LoadImage extends Activity {

private static final int SELECT_PICTURE = 1;

private String selectedImagePath;
private ImageView img;
Button buttonSave;
final Context context = this;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_load_image);

    img = (ImageView)findViewById(R.id.ImageView01);
    buttonSave = (Button) findViewById(R.id.button2);

    ((Button) findViewById(R.id.Button01))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
                }
            });
    buttonSave.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            img.setDrawingCacheEnabled(true);
            Bitmap bitmap = img.getDrawingCache();

            String root = Environment.getExternalStorageDirectory().toString();
            File newDir = new File(root + "/PARSE");
            newDir.mkdirs();
            Random gen = new Random();
            int n = 10000;
            n = gen.nextInt(n);
            String fotoname = "Photo-"+ n +".jpg";
            File file = new File (newDir, fotoname);
            if (file.exists ()) file.delete ();
            try {
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                Toast.makeText(getApplicationContext(), "Saved to your folder", Toast.LENGTH_SHORT).show();

            } catch (Exception e) {

            }
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

            // set title
            alertDialogBuilder.setTitle("Review the Answer?");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Click yes to submit answer!")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, close
                            // current activity
                            Intent intent = new Intent(LoadImage.this, TestImage.class);
                            ByteArrayOutputStream bs = new ByteArrayOutputStream();

                            intent.putExtra("byteArray", bs.toByteArray());

                            startActivity(intent);

                    }
        })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }
    });

}



public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }

    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
}

TestImage.java:

public class TestImage extends Activity {


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_image);

    Intent intent = getIntent();


    ImageView img = (ImageView) findViewById(R.id.ImageView01);

    if(getIntent().hasExtra("byteArray")) {
        ImageView previewThumbnail = new ImageView(this);
        Bitmap bitmap = BitmapFactory.decodeByteArray(
                getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
        previewThumbnail.setImageBitmap(bitmap);
    }

    Bundle extras = getIntent().getExtras();
    byte[] byteArray = extras.getByteArray("byteArray");

    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    img.setImageBitmap(bmp);
}
}

The 'intent' is the second activity is grey out stating variable 'intent' is never used.

Can someone help me to resolve this issue. Any help is much appreciated. Thank you.

UPDATED!!

LoadImage.java:

buttonSave.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            img.setDrawingCacheEnabled(true);
            final Bitmap bitmap = img.getDrawingCache();

            String root = Environment.getExternalStorageDirectory().toString();
            File newDir = new File(root + "/PARSE");
            newDir.mkdirs();
            Random gen = new Random();
            int n = 10000;
            n = gen.nextInt(n);
            String fotoname = "Photo-"+ n +".jpg";
            File file = new File (newDir, fotoname);
            if (file.exists ()) file.delete ();
            try {
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                Toast.makeText(getApplicationContext(), "Saved to your folder", Toast.LENGTH_SHORT).show();

            } catch (Exception e) {

            }
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

            // set title
            alertDialogBuilder.setTitle("Review the Answer?");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Click yes to submit answer!")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, close
                            // current activity
                            Intent intent = new Intent(LoadImage.this, TestImage.class);
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                            byte[] bytes = stream.toByteArray();
                            intent.putExtra("bitmapbytes",bytes);

                            startActivity(intent);

                    }
        })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }
    });

}

TestImage.java:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_image);

    byte[] bytes = getIntent().getData().getByteArrayExtra("bitmapbytes");
    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    ImageView img = (ImageView) findViewById(R.id.ImageView01);


    img.setImageBitmap(bmp);
}
}
marian
  • 277
  • 1
  • 5
  • 17

4 Answers4

1

Bitmap implements Parcelable, so you could always pass it in the intent:

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);

and retrieve it on the other end:

Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Suhas Bachewar
  • 1,230
  • 7
  • 21
  • ive change the coding as u suggested : Intent intent = getIntent(); Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage"); ImageView img = (ImageView) findViewById(R.id.ImageView01); img.setImageBitmap(bitmap); – marian Jan 22 '16 at 06:12
  • Now the 'bitmap' is in grey colour with message 'Casting 'intent.getParcelableExtra("BitmapImage") to Bitmap is redundant. @Suhas B – marian Jan 22 '16 at 06:15
1

Activity

To pass a bitmap between Activites

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

And in the Activity class

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

Fragment

To pass a bitmap between Fragments

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

To receive inside the SecondFragment

Bitmap bitmap = getArguments().getParcelable("bitmap");

Transferring large bitmap (Compress bitmap)

If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

In the FirstActivity

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

And in the SecondActivity

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
capt.swag
  • 10,335
  • 2
  • 41
  • 41
  • i used the coding for activities and in the second activity the 'intent' is grey stating 'intent is never used' and the 'Bitmap' is also grey stating 'Casting 'intent.getParcelableExtra("bitmap") to Bitmap is redundant. @4k3R – marian Jan 22 '16 at 06:20
  • that means, you don't have to cast it to Bitmap. So you can remove (Bitmap) from getIntent().getParcelableExtra("bitmap"). I have updated the answer – capt.swag Jan 22 '16 at 06:22
  • Grey color means, Android Studio is telling you that you are not using the Bitmap anywhere else. It's not an issue. Just a message. – capt.swag Jan 22 '16 at 06:23
  • okay but the image is not passed to the second layout. Logcat: – marian Jan 22 '16 at 06:25
  • noteapp E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!! noteapp E/ViewRootImpl﹕ sendUserActionEvent() mView == null E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!! noteapp E/ViewRootImpl﹕ sendUserActionEvent() mView == null – marian Jan 22 '16 at 06:26
  • Ive tried ur updated suggestion. now the error is 'cannot resolve getByteArrayExtra' – marian Jan 22 '16 at 07:05
  • i have posted the updated coding above. tq so much fr helping me out. – marian Jan 22 '16 at 07:05
  • Finally found the issue, no need to call getIntent().getData(), instead you can directly use getIntent().getByteArrayExtra(). I have updated the answer again. – capt.swag Jan 22 '16 at 07:07
  • THANK YOU SO MUCH FOR UR HELP N PATIENCE :) its working fine now...thank you again :) :) – marian Jan 22 '16 at 07:10
0

Yes You can send Bitmap through Intent

Intent intent =new Intent(Context ,YourActivity.class); intent.putExtra("key",bitmap);

To receive the bitmap in YourActivity.class

Intent intent=getIntent(); Bitmap image=intent.getParcelableExtra("key");

This will work fine for Small Size bitmap

When the size of Bitmap is large it will Fail to send through Intent. Beacuse Intent are mean to send small set of data in key value pair.

For this You can send the Uri of the Bitmap through Intent

  Intent intent =new Intent(Context ,YourActivity.class);
  Uri uri;// Create the Uri From File Or From String.
  intent.putExtra("key",uri);

In your YourActivity.class

   Intent intent=getIntent();
   Uri uri=intent.getParcelableExtra("key");

Create the Bitmap From the Uri.

Hope It will help you.

BalaramNayak
  • 1,295
  • 13
  • 16
0

maybe your bitmap is too large.And you will find FAILED BINDER TRANSACTION in your logcat. So just take a look at FAILED BINDER TRANSACTION while passing Bitmap from one activity to another

Community
  • 1
  • 1
sunday
  • 48
  • 6