Can't upload image from Gallery

白昼怎懂夜的黑 提交于 2019-12-03 21:43:58
        private static final int SELECT_PICTURE = 1;
        private String selectedImagePath, filemanagerstring;
        private static File myFile = null;

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(Intent.createChooser(intent,
                "Select Picture"), SELECT_PICTURE);

onActivity result::

           if (data != null) {
            Uri selectedImageUri = data.getData();
            filemanagerstring = selectedImageUri.getPath();
            selectedImagePath = getPath(selectedImageUri);

            if (selectedImagePath != null)
                myFile = new File(selectedImagePath);
            else if (filemanagerstring != null)
                myFile = new File(filemanagerstring);

            if (myFile != null) {

                Bitmap bmp_fromGallery = decodeImageFile(selectedImagePath);


                System.out.println("Bitmap is :: " + myPhoto_bitmap);
                //SET BITMAP TO IMAGEVIEW
            } else {
                Toast.makeText(getApplicationContext(),
                        myFile.getName() + "is null", Toast.LENGTH_LONG)
                        .show();
            }
        } else {
            Toast.makeText(SelectPhoto.this, "Please Select Image!!!",
                    Toast.LENGTH_LONG).show();
        }

You cannot send anything with a value of null in eclipse. You will always get a nullPointerException.

Caused by: java.lang.NullPointerException
at com.csun.spotr.UploadImageActivity.onActivityResult(UploadImageActivity.java:42)

The first at line under cause is the line number of code that is throwing the err

 CircleImageView profile;
Bitmap bmp;
SharedPreferences sp;
public static final int PERMISSION_REQUEST_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 1;

onCreate() method :

 sp=getSharedPreferences("profilePicture",MODE_PRIVATE);
    profile=(CircleImageView)findViewById(R.id.profile);
    if(!sp.getString("dp","").equals("")){
        byte[] decodedString = Base64.decode(sp.getString("dp", ""), Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        profile.setImageBitmap(decodedByte);
    }

 profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery();
        }
    });

openGallery()

 private void openGallery() {
    if (ActivityCompat.checkSelfPermission(ProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(ProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
    }
    else {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 1);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
{
    switch (requestCode) {
        case PICK_FROM_GALLERY:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
            } else {
                Toast.makeText(ProfileActivity.this,"Not working",Toast.LENGTH_LONG).show();
                //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
            }
            break;
    }
}

onActivityResult

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

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        try {
            // When an Image is picked
            if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                // Set the Image in ImageView after decoding the String
                bmp = BitmapFactory
                        .decodeFile(imgDecodableString);
                profile.setImageBitmap(bmp);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
                sp.edit().putString("dp", encodedImage).commit();
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
        }

    }else {
        Toast.makeText(ProfileActivity.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
    }
}

Method for Choosing an image

private void showImageChooser(){

    Intent intent= new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Your Profile Picture"),CHOOSE_IMAGE)
}     

"Uri = uriprofileImage" (Create this Variable globally inside the AppCompactAcivity)

OnActivityResult Method

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

    if(requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data!=null && data.getData() != null) {

        uriprofileImage =  data.getData();

        try {
            //getting the image
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uriprofileImage);

            //displaying the image
            imageView.setImageBitmap(bitmap);


        } catch (IOException e) {

            e.printStackTrace();

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!