-4

I am able to view the gallery fine through the dialog, however when I select the image I want it closes the gallery and doesn't appear to update the bitmap on the ImageView, or store it as actualprofilepicture.jpg so I can load it when I want.

The issue seems to be when calling galleryResult() and using Bitmap thumbnail = (Bitmap) data.getExtras().get("data); which gives the following errors;

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.BaseBundle.get(java.lang.String)' on a null object reference at com.example.android.myapplication.personalHome.galleryResult(personalHome.java:143) at com.example.android.myapplication.personalHome.onActivityResult(personalHome.java:132)

I have absolutely no issue using the Camera API, taking picture and saving it.

package com.example.android.myapplication;

    import android.app.Activity;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.content.Intent;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.widget.ImageView;

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;

    import static android.R.attr.data;
    import static android.R.attr.thumbnail;
    import static android.provider.LiveFolders.INTENT;
    import static android.widget.ImageView.ScaleType.FIT_CENTER;

    public class personalHome extends AppCompatActivity {

        private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
        private String userChoosenTask;
        ImageView profileimage;

    //Camera/Image code inspired and based from http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.personal_home);
            getFilesDir().getAbsolutePath();
            View camera = findViewById(R.id.camera);

            //the code here retrieves the selected profile picture if it exists and loads it
            File imgFile = new  File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "actualprofilepicture.jpg");
            if(imgFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                ImageView myImage = (ImageView) findViewById(R.id.profilepic1);
                myImage.setImageBitmap(myBitmap);
                //profile picture is now set in imageview on the page
            }

            camera.setOnClickListener(new View.OnClickListener(){

                public void onClick(View v){
                    selectImage();
                }


            });
        }

        public void selectImage() {
            final CharSequence[] items = { "Take Photo", "Choose from Library",
                    "Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(personalHome.this);
            builder.setTitle("Add Photo!");

            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    boolean result = Utility.checkPermission(personalHome.this);
                    if (items[item].equals("Take Photo")) {
                        userChoosenTask = "Take Photo";
                        if(result)
                            cameraOpen();
                    } else if (items[item].equals("Choose from Library")) {
                        userChoosenTask = "Choose from Library";
                        if(result)
                            galleryOpen();
                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
        public void cameraOpen() {
            Intent openCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(openCamera, 0);
        }

        private static int RESULT_LOAD_IMAGE = 1;
        public static final int PICK_IMAGE = 1;

        private void galleryOpen()
        {
           /** Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
    **/
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, SELECT_FILE);
            System.out.println("this works at galleryopen()");

            //intent.setType("image/*");
            //intent.setAction(Intent.ACTION_GET_CONTENT);
            //startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);


        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            System.out.println("this works BEFORE requestcode == SELECT_FILE");

            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == SELECT_FILE) {
                    Log.d("HELLO", "this works ");
                    System.out.println("this works at requestcode == SELECT_FILE");
                    galleryResult(data);
                }
                else if (requestCode == REQUEST_CAMERA) {
                    onCaptureImageResult(data);
                }
            }
        }

        private void galleryResult(Intent data) {

            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

            File destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "actualprofilepicture.jpg");
            personalHome.this.getFilesDir().getAbsolutePath();
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            setContentView(R.layout.personal_home);
            profileimage.findViewById(R.id.profilepic1);
            profileimage.setImageBitmap(thumbnail);

            System.out.println("this works finally...or not");

            Intent loadPersonal = new Intent(personalHome.this, personalHome.class);
            startActivity(loadPersonal);
        }

        private void onCaptureImageResult(Intent data) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

            /**destination of the file is set as PICTURES folder in the internal storage of device
             *   -- this stores the profile picture for when you next load the app
             */
            File destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "actualprofilepicture.jpg");
            personalHome.this.getFilesDir().getAbsolutePath();
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            setContentView(R.layout.personal_home);
            profileimage = (ImageView) findViewById(R.id.profilepic1);
            profileimage.setImageBitmap(thumbnail);

            Intent loadPersonal = new Intent(personalHome.this, personalHome.class);
            startActivity(loadPersonal);
        }

    }
Hazed 2.0
  • 135
  • 9
  • Actually nevermind I am a complete idiot. I was using the wrong object (profileimage) to change the imageview. I was supposed to instantiate the imageview using like I did at the top of the code. ImageView myImage = (ImageView) findViewById(R.id.profilepic1); myImage.setImageBitmap(myBitmap); ...which explains why it wasn't working. Fixed it now. Sorry for wasting everyone's time ! – Hazed 2.0 Mar 26 '18 at 20:51

2 Answers2

1

ACTION_PICK does not return a Bitmap in a "data" extra. It returns a Uri that you can pass to your favorite image-loading library (e.g., Glide, Picasso). Or, use it with a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri.

CommonsWare
  • 910,778
  • 176
  • 2,215
  • 2,253
0

Actually nevermind I am a complete idiot.

I was using the wrong object (profileimage) to change the imageview. I was supposed to instantiate the imageview using like I did at the top of the code.

ImageView myImage = (ImageView) findViewById(R.id.profilepic1); myImage.setImageBitmap(myBitmap);

...which explains why it wasn't working. Fixed it now. Sorry for wasting everyone's time !

Hazed 2.0
  • 135
  • 9