Null Pointer Exception while choosing file - java

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();
}
}

Related

Android 10, select a photo from the gallery

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

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();
}
}

I compressed bitmap of image but it wouldn't go to the next activity

I am developing an android app. In this after taking a picture from gallery it will go to next page. but when I use small size of image,it works. But larger size is not working. I compressed bitmap. But still now problem exists.
Homepage.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && 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();
}
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && 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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(imgDecodableString);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
// Set the Image in ImageView aimgView.setImageBitmap(bitmap);
Toast.makeText(this, "Picture loaded Successfully", Toast.LENGTH_LONG).show();
nextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myintent = new Intent(HomePage.this, Image_Recognition.class);
myintent.putExtra("picture", byteArray);
startActivity(myintent);
}
});
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
}
Picture.java
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
final Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
The logcat is "JavaBinder: !!! FAILED BINDER TRANSACTION !!!"
It's very necessary for my app. But I can't find any solution of this.

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.

Getting image extension

In the application the user can select an image. To start the gallery I use the following code:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
When I print the path in onActivityResult method, I get the image path like /external/images/media/5615. I'd like to know the image extension, because the image needs to be uploaded to a server. The extension may vary.
What you're getting is a path the MediaStore uses to get the Images. The following code will take the result from your Intent, and get the filename attached to it:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY_SELECT_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
Log.i(TAG, "" + selectedImage.toString());
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();
Log.i(TAG, "" + picturePath);
//Do whatever with picturePath
}

Categories

Resources