-4

我可以通过对话框很好地查看图库,但是当我选择我想要的图像时,它会关闭图库并且似乎不会更新 ImageView 上的位图,或者将其存储为 actualprofilepicture.jpg 以便我可以加载它我想。

问题似乎是在调用 galleryResult() 并使用 Bitmap thumbnail = (Bitmap) data.getExtras().get("data); 时出现以下错误;

原因:java.lang.NullPointerException:尝试在 com.example.android.myapplication.personalHome 的空对象引用上调用虚拟方法“java.lang.Object android.os.BaseBundle.get(java.lang.String)” .galleryResult(personalHome.java:143) 在 com.example.android.myapplication.personalHome.onActivityResult(personalHome.java:132)

使用 Camera API,拍照并保存它绝对没有问题。

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);
        }

    }
4

2 回答 2

1

ACTION_PICK不会额外返回Bitmapa 。"data"它返回一个Uri你可以传递给你最喜欢的图像加载库(例如,Glide、Picasso)。或者,将其与 a ContentResolverand一起使用openInputStream()以获取InputStreamUri.

于 2018-03-26T17:49:41.580 回答
0

其实没关系,我是一个彻头彻尾的白痴。

我使用了错误的对象(profileimage)来更改 imageview。我应该像在代码顶部那样使用实例化图像视图。

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

...这解释了为什么它不起作用。现在修好了。很抱歉浪费了大家的时间!

于 2018-03-26T20:50:24.307 回答