-1

I'm trying to pass an image to another class through intent, but it only works for captured image, not for image selected from gallery.

This is where the camera function get started.In ImageFitScreen.java, it has a ok button used to return back to the previous activity.

ImageFitScreen.java

 public void selectImage() {

        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(ImageFitScreen.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int item) {

                if (options[item].equals("Take Photo"))

                {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");


                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    //pic = f;
                  //  Toast.makeText(getApplicationContext(), Uri.fromFile(f) +"", Toast.LENGTH_LONG).show();
                    startActivityForResult(intent, 1);


                } else if (options[item].equals("Choose from Gallery"))

                {

                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(intent, 2);


                } else if (options[item].equals("Cancel")) {

                    dialog.dismiss();
                    finish();

                }

            }

        });

        builder.setOnKeyListener(new Dialog.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK){
                    dialog.dismiss();
               finish();
            }

            return true;
        }
        });
        builder.show();



    }



    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                //h=0;
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                        //pic = photo;
                        break;
                    }
                }

                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmapOptions.inJustDecodeBounds = false;
                    bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
                    bitmapOptions.inDither = true;
                    bitmapOptions.inSampleSize=8;
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
                    Global.img = bitmap;

                    b.setImageBitmap(bitmap);
                    String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
                    //p = path;
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {

                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        //pic=file;
                        outFile.flush();
                        outFile.close();


                    } catch (FileNotFoundException e) {
                        e.printStackTrace();

                    } catch (IOException e) {
                        e.printStackTrace();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }

            } else if (requestCode == 2) {

                Uri selectedImage = data.getData();
                // h=1;
                //imgui = selectedImage;
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.w("path of image ******", picturePath + "");
                b.setImageBitmap(thumbnail);
            }


        }
        else
        {
            finish();
        }




 ok.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent returnIntent=new Intent();
                text=t.getText().toString();
                b.setDrawingCacheEnabled(true);
                b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
                b.buildDrawingCache(true);
                returnIntent.putExtra("text", text);
                if (b.getDrawingCache() != null) {
                    Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
                    if (bitmap == null) {
                        Log.e("TAG", "getDrawingCache() == null");
                    }
                    Global.img = bitmap;
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

Previous Activity

     public void onActivityResult(int requestCode,int resultCode, Intent data)
        {
            if(requestCode==PROJECT_REQUEST_CODE) {
                if(data!=null&&data.hasExtra("text")) {
                    c = data.getStringExtra("text");
                    txt1.setText(c);
                    viewImage.setImageBitmap(Global.img); // image can be displayed
                }


            }
            else if (requestCode==CAMERA_REQUEST_CODE)
            {

            }
        }

   b.setOnClickListener(new View.OnClickListener() {  // save button
            public void onClick(View arg0) {
                Intent returnIntent = new Intent();
                a = "Project";
                text = txt.getText().toString(); // amount
                returnIntent.putExtra("text", text);
                returnIntent.putExtra("a", a);
                final int k1 = getIntent().getExtras().getInt("k");
                returnIntent.putExtra("k1", k1);
                returnIntent.putExtra("c",c);
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

    }

**The image can be returned to Previous Activity ** since it can display in viewImage. In previous activity, it also has a button back to Activity A.

Activity A

   c = (TextView) claims.findViewById(R.id.textView49);
     c.setOnClickListener(new View.OnClickListener() {
                                     @Override
                                     public void onClick(View v) {
                                         if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
                                             Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
                                             Intent intent = new Intent(getActivity(), EditClaims.class);
                                             intent.putExtra("name", name);
                                             intent.putExtra("result", result);
                                             intent.putExtra("description", description);

                                        byte[]data=getBitmapAsByte(getActivity(), Global.img);
                                             intent.putExtra("data",data);
                                             startActivity(intent);

                                             }
                                         else {
                                             Toast.makeText(getActivity().getApplicationContext(), "null", Toast.LENGTH_LONG).show();
                                         }
                                     }
                                         } );

      public static byte[]getBitmapAsByte(final Context context,Bitmap bitmap) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, outputStream);
            return outputStream.toByteArray();

        }

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        int button = data.getIntExtra("k1", 0);

        if (button == 1) {
            switch (requestCode) {
                case 0:
                    result = data.getStringExtra("text");
                    name = data.getStringExtra("a");
                    description=data.getStringExtra("c");
                    if (Global.img != null) {
                        v.setImageBitmap(Global.img);
                    }

                         as=Long.parseLong(result);
                        c.setText("            " + name + "------" + "RM " + result);
                        break;
  }
        }
       else if(requestCode==CAMERA_REQUEST_CODE)
        {

        }

Activity B (Activity)

 if(getIntent().hasExtra("data")) {
           // ImageView previewThumbnail = new ImageView(this);
            Bitmap b = BitmapFactory.decodeByteArray(
                    getIntent().getByteArrayExtra("data"),0,getIntent().getByteArrayExtra("data").length);
            viewImage.setImageBitmap(b);
        }

Global.java

public class Global {

    static Bitmap img;
}

When it intent to Activity B, my app will exit automatically. But it will works if the image is captured image. Is it because the size too large? I have no ide on this.Can someone help me? Thanks a lot!

Hoo
  • 1,806
  • 7
  • 33
  • 66
  • do you have any error log?? – calvinfly Nov 11 '15 at 06:32
  • @calvinfly No.. app exit without given any error – Hoo Nov 11 '15 at 06:36
  • I follow [this](http://www.jayrambhia.com/blog/pass-activity-bitmap/) but no success.. – Hoo Nov 11 '15 at 06:38
  • check is data.length>0, you may understand the problem clearer – misman Nov 11 '15 at 06:46
  • @mismanc where to check – Hoo Nov 11 '15 at 06:54
  • if(data.length>0){intent.putExtra("data",data); startActivity(intent);} – misman Nov 11 '15 at 07:40
  • Do you keep the captured image in **Global.img**, too? How do you put it there? – Alex Cohn Nov 11 '15 at 07:57
  • @AlexCohn `Captured image` and `selected image from gallery` are using same coding – Hoo Nov 11 '15 at 08:09
  • Sorry, how do you capture the image? Do you use `MediaStore.ACTION_IMAGE_CAPTURE` intent? Do you load the bitmap from `extras.get("data")` in `onActivityResult()`? – Alex Cohn Nov 11 '15 at 08:20
  • @AlexCohn wait..I editing my post :0 – Hoo Nov 11 '15 at 08:21
  • @AlexCohn I'm sorry if the code are a bit long..Please don't hesitate to tell me if you still don't understand my problem – Hoo Nov 11 '15 at 08:43
  • Anyone can help? I need help seriously – Hoo Nov 11 '15 at 09:04
  • you should get the path of the image in `String` variable and pass to next `Activity`, then decode as a `Bitmap` from image path in next `Activity` – Zubair Ahmed Nov 11 '15 at 09:11
  • @ZubairAhmadKhan but why it can display on `viewImage`? – Hoo Nov 11 '15 at 09:14
  • have you seen this answer? http://stackoverflow.com/a/11010565/2311051 – Zubair Ahmed Nov 11 '15 at 09:15
  • @ZubairAhmadKhan tried but no luck :( – Hoo Nov 11 '15 at 09:45
  • Note: for captured image, you use [inSampleSize](http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize) = 8, but for gallery you load the file at full size. That is likely to make the difference. – Alex Cohn Nov 11 '15 at 10:48
  • As @ZubarAhmadKhan noted [above](http://stackoverflow.com/questions/33644614/failed-to-pass-image-to-another-class?noredirect=1#comment55068068_33644614), there is no advantage in passing the huge bitmap via Intent. This mechanism is by no means intended to pass huge data. If you pass the file name, then the consumer activity can choose the best subsampling to fit the view size. – Alex Cohn Nov 11 '15 at 10:54
  • I've run into two issues with this in the past. 1. Passing images through an Intent is not ideal because of the size limit. I've typically saved the image in shared preferences in the past. 2. I've had an issue before on lollipop where onActivityResult(int requestCode, int resultCode, Intent data) would get back a null or empty data object if the code was selected from gallery. Have you checked to see if data isn't null after you select your image in onActivityResult? –  Nov 11 '15 at 16:35
  • @Killingsworth ya,it is not null. I wonder why the image can return to previous activity but cannot intent to next activity – Hoo Nov 11 '15 at 16:38
  • so, are you using the global variable to store the image between activities or are you passing it via the intent as you stated? You should only use one. –  Nov 11 '15 at 16:50
  • Also, why do you have an onActivityResult in all of these activities? Why do you not just have one for the picture taker activity? –  Nov 11 '15 at 16:53
  • @Killingsworth I only can use one ? – Hoo Nov 11 '15 at 17:06

2 Answers2

1

You shouldn't put bitmap into Bundle. The best way is saving image on storage and pass path uri between activities.

Artur Movsesyan
  • 744
  • 6
  • 21
-1
byte [] recieve = getIntent().getByteArrayExtra("key",defaultValue);
user5534193
  • 145
  • 2
  • i already have `getIntent().getByteArrayExtra("data"),0,getIntent().getByteArrayExtra("data").length);` in Activity B – Hoo Nov 11 '15 at 05:20