Pardyot Shahi February 2016

Couldn't upload a picture using google photos

I used this piece of code to get the image from the gallery and then crop the image before saving it. Its running up and nicely for android built in gallery but giving NullPointerException in onActivityResult method where we get extras.getParcelable("data") on using google photos app on android. Any help would be appreciated. Thanks in advance :D

//This is called in oncreate() on clicking the upload from gallery button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK ,    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
galleryIntent.putExtra("crop", "true");
startActivityForResult(galleryIntent,PICK_FROM_FILE);

//This is called on onActivityResult() method
if (requestCode == PICK_FROM_FILE && data != null) {
    Bundle extras = data.getExtras();
    //get the cropped bitmap from extras
    Bitmap thePic = extras.getParcelable("data");
    //do whatever with thePic
}

Answers


Shubham Chaudhary February 2016

It worked for me.

//This is my onActivityResult method.
if (resultCode == RESULT_OK && data != null) {
    final Uri selectedImage = data.getData();

    String root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    File createDir = new File(root + "AppName" + File.separator);
    if (!createDir.exists()) {
        createDir.mkdirs();
    }
    SimpleDateFormat s = new SimpleDateFormat("ddMMyyyhhmmss");
    String format = s.format(new Date());
    File file = new File(root + "AppName" + File.separator + format);

    if (!file.exists()) {
        try {
            file.createNewFile();
            copyFile(new File(getRealPathFromURI(selectedImage)), file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String filePath = file.GetAbsolutePath();
    Bitmap bitmap = BitmapFactory.decodeFile(filepath);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
    int height = bitmap.getHeight();
    int width = bitmap.getWidth();
    Bitmap bmp = Bitmap.createScaledBitmap(bitmap, 100, 100, true);

    mImageView.setImageBitmap(bmp);

}

And this is the copyFile method that i have used in this.

private void copyFile(File sourceFile, File destFile) throws IOException {
    if (!sourceFile.exists()) {
        return;
    }

    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }
}

Hope it works for you as well :D

Post Status

Asked in February 2016
Viewed 1,094 times
Voted 11
Answered 1 times

Search




Leave an answer