从图库中选择图片作为个人资料图片不起作用.- onActivityResult()

时间:2018-03-26 17:47:08

标签: java android gallery onactivityresult profile-picture

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

问题似乎是在调用galleryResult()并使用Bitmap thumbnail =(Bitmap)data.getExtras()。get(“data); 这会产生以下错误;

  

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.Object android.os.BaseBundle.get(java.lang.String)'                                                                                          在com.example.android.myapplication.personalHome.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);
        }

    }

2 个答案:

答案 0 :(得分:1)

ACTION_PICK不会在Bitmap额外内容中返回"data"。它会返回Uri,您可以将其传递给您最喜爱的图像加载库(例如,Glide,Picasso)。或者,将其与ContentResolveropenInputStream()一起使用,以获得InputStream标识的内容的Uri

答案 1 :(得分:0)

实际上没关系,我是一个完全白痴。

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

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

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