Android 10, select a photo from the gallery - java

people. I'm trying to get a photo from the Android 10 gallery. But, it tells me that bitmap = null, code below, what's wrong?
public void createIntent() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
if(Build.VERSION.SDK_INT < 29 ) {
this.bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} else {
this.bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.getContentResolver(), uri));
}

This is working on Android 10 also for me.
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String imagePath = getPath(data.getData());
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(imagePath),
null, options);
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "Error loading the bitmap from the path: "
+ imagePath, e);
}
}
private String getPath(Uri uri) {
String path = "";
Cursor cursor = null;
try {
String[] projection = { MediaColumns.DATA };
cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor == null || !cursor.moveToFirst()) {
path = "";
} else {
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
path = cursor.getString(columnIndex);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return path;
}

I have created the solution.
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uri = data.getData();
InputStream stream = this.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(stream);
}
This code works for Build.VERSION.SDK_INT < 29 and for Build.VERSION.SDK_INT >= 29

Related

i want to crop an image to set profile

I am new here and learning about android development. I want to crop image to set profile pic. when i used below codes its not done its jump to catch(something went wrong). kindly please help me solve this problem. used Image view on xml and got permission read and write on mainfest. And used ArthurHub/Android-Image-Cropper for cropping function
enter code here select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
premission();
if (pre == 2) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
Log.d("pp", "pp");
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && null != data)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
Uri selectedImage = data.getData();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
Uri selectedImage = result.getUri();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
profileimage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
Drawable myDrawable = profileimage.getDrawable();
profileimage.buildDrawingCache();
Bitmap bmap = profileimage.getDrawingCache();
BitmapDrawable bitmapDrawable = ((BitmapDrawable) myDrawable);
Bitmap bitmap1 = bitmapDrawable.getBitmap();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, stream);
imageInByte = stream.toByteArray();
encoded = Base64.encodeToString(imageInByte, Base64.DEFAULT);
} else
{
Toast.makeText(this, "You have not picked Image",
Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}

Null Pointer Exception while choosing file

I am writing a contact form in which I am creating a file picker with a button, but the problem is that if file size is large, its unfortunately stops and if there is no file explorer than its giving null pointer exception.
Here is the code of intent
Intent intent= new Intent(Intent.ACTION_PICK);
intent.setAction(Intent.ACTION_GET_CONTENT);// its optional
intent.setType("image/*");
final int SELECT_IMAGE = 1;
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_IMAGE);
and here is the code of on activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 1 && resultCode == RESULT_OK ) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
//this code converts image in base64 and the string is to be sent along post method:
yourSelectedImage = BitmapFactory.decodeFile(filePath);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, resultCode, Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}

ImageView not showing image selected from gallery

So I have a button that loads the gallery, and selects an image using this code...
public void getGalleryImage(View v){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
But when it goes back to the original activity, the ImageView still doesn't show anything. It doesn't give me any errors, or anything like that. Here the XML for the ImageView...
<ImageView
android:id="#+id/galleryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
How can I get it to show?
I ended up figuring something out. I just did...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageURI(selectedImage);
}
This worked for what I was trying to accomplish.
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri));
}
}
public class MainActivity extends AppCompatActivity{
ImageView image;
Button pick;
int TAG_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
pick = (Button) findViewById(R.id.button);
pick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,"Select Image "),TAG_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAG_IMAGE && resultCode == RESULT_OK )
{
Uri selectedImage = data.getData();
try
{
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String images = cursor.getString(columnIndex);
image.setImageURI(selectedImage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

android camera takePicture goes wrong

logcat message remind:
failure delivering result ResultInfo{who = null,request=131073,result=-1,date=null}
fatal exception at com.example.newpingziyi.FindFragment.doPhoto(FindFragment.java:178);
178lines:
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
onActivityResult after photos pick up
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
doPhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doPhoto(int requestCode, Intent data) {
if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
if (data == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if (photoUri == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
}
String[] pojo = { MediaColumns.DATA };
// fatal exception
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try {
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, "error:" + e);
}
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null) {
Intent startEx = new Intent(getActivity(), PhotoPre.class);
startEx.putExtra(SAVED_IMAGE_DIR_PATH, picPath);
startActivity(startEx);
} else {
Toast.makeText(getActivity(), R.string.photo_err, Toast.LENGTH_LONG)
.show();
}
}
use this
cursor.moveToLast();
instead of cursor.moveToFirst();

loading image into an imageView

i am a new android developer my first task with Intent is to pick an image from gallery and display it into an imageview so what i did is the following :
xml:
<Button
android:id="#+id/Intent_btn"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/button1"
android:text="Intent button"
android:onClick="openGallery" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignRight="#+id/Intent_btn"
android:layout_centerVertical="true" />
code:
ImageView imageview1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview1=(ImageView)findViewById(R.id.imageView1);
}
public void openGallery(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
imageview1.setImageBitmap(yourSelectedImage);
}
}
i managed to open the gallery and pick an image but it never load what would it be the problem ?
Add Permission to manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here's some sample code on how to do that:
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
}
Add this permission :-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use this. This will work. Put this code in onActivityResult()
Uri selectedImage = data.getData();
String galleryImatePath = getRealPathFromURI(selectedImage);
InputStream stream = getContentResolver().openInputStream(selectedImage);
final Bitmap myImage = BitmapFactory.decodeStream(stream, null , bfOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.JPEG, 100, bos);
imageview1.setImageBitmap(myImage);
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
image.setImageBitmap(bitmap);
saveToInternalSorage(bitmap);
// save image to internal memory
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try as like this.

Categories

Resources