In my app, user can choose an image, that I save in internal memory.
My code works perfecly if I choose an image that is in internal memory, but if I choose an image that is on the cloud (Drive or Photo) it doesn't work and it save an 0bit image.
The code is in a fragment.
This is a part of my code:
First, I choose the image with
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
Then, I save the image with
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Bitmap imageSelect = BitmapFactory.decodeFile(picturePath);
cursor.close();
ContextWrapper cw = new ContextWrapper(getContext());
File directory = cw.getDir("images",Context.MODE_PRIVATE);
File myPath = new File(directory,"defaultwallpaper.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
imageSelect.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if (fos!=null){
fos.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
And I have this errors:
E/BitmapFactory: Unable to decode stream: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
I solved it by changing the code and it works on my Nexus 5 with Android 6:
Uri uri = data.getData();
/*String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
imageSelect = BitmapFactory.decodeFile(picturePath);
cursor.close();*/
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}