I'm having a simple problem that may seem easy, however, when I pick a image from the gallery and try to set it up the in imageview in onActivityResult, the error would show up.
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/35 }} to activity {com.mypackagename/com.mypackagename.SQLiteActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This error must be due to the null object. That would mean that no data was retreived? I percieve that the settings that I made had no problem, however, I may have missed something. I've set the sample code below.
This is the code that calls the gallery
public void settingImage(View v){
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
This code is for getting the results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
// Log.d("Path", picturePath);
//sampleimage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
// imgPath = picturePath;
icontext.setText(picturePath);
cursor.close();
} else {
}
}
Here's some settings
private static int RESULT_LOAD_IMAGE = 1;
basic sdk setup
minSdkVersion 14
targetSdkVersion 22
I have try this to get Bitmap,
code that calls the gallery picker,
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
getting the results of bitmap,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
//yourSelectedImage = BitmapFactory.decodeStream(imageStream);
try {
yourSelectedImage = decodeUri(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// imgViewProfilePic.setImageBitmap(yourSelectedImage);
}
}
}
to decode uri,
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 140;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
Related
I'm trying to create simple Contact app. Naturally there is Contact class with member variable mCurrentPhotoPath. An activity which is responsible for creating Contact, has an option to pick image from Gallery in the following way:
final Intent pickImage = new Intent(Intent.ACTION_GET_CONTENT);
pickImage.setType("image/*")
/*some code...*/
galleryButton.setOnClickListener((View v) -> {
startActivityForResult(pickImage, REQUEST_GALLERY_PHOTO);
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK){
photoTaken = true;
Uri selectedImage = data.getData();
Log.i("path", selectedImage.getPath()) //prints out: /document/image:292562
mPhotoView.setImageURI(selectedImage);
I am able to display selected image in ImageView (mPhotoView).
However, when I try to set Intent in different way, I get full path, but I cannot recreate file from that path and I get FileNotFoundException.
final Intent pickImage = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK){
photoTaken = true;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.i.("TAG", picturePath); //I get, /storage/emulated/0/Pictures/Viber/IMG-bbd54c96cc971a1700f92205937014c8-V.jpg
mPhotoFile = new File(picturePath);
cursor.close();
updatePhotoView(); //This method recreates image based on exact file path and witdh & height of ImageView where the picture is going to be placed;
}
}
}
Here is updatePhotoView()
private void updatePhotoView(int imageWidth, int imageHeight) {
if (mPhotoFile == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
Bitmap bitmap = PictureUtils.getScaledBitmap(mPhotoFile.getPath(),imageWidth, imageHeight); // imageWidth & imageHeight are member variables of actiivty...
mPhotoView.setImageBitmap(bitmap);
}
}
I'm pretty sure this function works, because when I implemented option to take picture from camera (I created file with getExternalFilesDir(), and in any other activity when I passed string value of mCurrentPhotoPath, getScaledBitmap() managed to recreate image).
Here is getScaledBitmap():
public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight) {
// Read in the dimensions of the image on disk
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
// Figure out how much to scale down by
int inSampleSize = 1;
if (srcHeight > destHeight || srcWidth > destWidth) {
if (srcWidth > srcHeight) {
inSampleSize = Math.round(srcHeight / destHeight);
} else {
inSampleSize = Math.round(srcWidth / destWidth);
}
}
options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
// Read in and create final bitmap
return BitmapFactory.decodeFile(path, options);
}
Just if anyone stumbles on similar problem. I solved my problem of getting images by using Glide library. Look it up, bunch of tutorials. I guess that this load function is doing heavy lifting in the background. Great thing! Here is how code looks like:
Glide.with(context)
.load(imageFilePath)
.apply(new RequestOptions().centerCrop())
.override(imageView.getWidth(), imageView.getHeight())
.into(imageView);
I m selecting Image From Gallery and crop in My Phone And Uploading To Server ..
When i m testing Someother devices then
image was Unable Picked to some devices
public void selectImageFromGallery() {
String TEMP_PHOTO_FILE = "temporary_holder.jpg";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, PICK_IMAGE);
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),"temporary_holder.jpg");
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
File tempFile = getTempFile();
String filePath= Environment.getExternalStorageDirectory()
+"/"+"temporary_holder.jpg";
System.out.println("path "+filePath);
decodeFile(filePath);
if (tempFile.exists()) tempFile.delete();
}
}
}
}
/**
* The method decodes the image file to avoid out of memory issues. Sets the
* selected image in to the ImageView.
*
* #param filePath
*/
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
roundedImage=new RoundedImage(bitmap);
image.setImageDrawable(roundedImage);
}
here Is My Code
please Tell ME Where I m Doing Wrong
I want To Remove To Create An New File On Sd Card if Sd Card Is Not Available on no space
app Crashed
//Initialize variable
int select_photo = 1;
//Make this method to start intent
void Profile_Image_Pick() {
Intent in = new Intent(Intent.ACTION_PICK);
in.setType("image/*");
startActivityForResult(in, select_photo);
}
//Now on ActivityforResult
#Override
protected void onActivityResult(int requestCode, int resultCode,
super.onActivityResult(requestCode, resultCode, imagereturnintent);
switch (requestCode) {
case select_photo:
if (resultCode == RESULT_OK) {
final Uri imageuri = imagereturnintent.getData();
final InputStream imageStream = getContentResolver()
.openInputStream(imageUri);
bitmap = BitmapFactory.decodeStream(imageStream);
Bitmap bt = Bitmap.createScaledBitmap(bitmap, 70, 70, false);
profile_image.setImageBitmap(bt);
}
}
}
//for checking sdcard is present or not you can use
if(android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
//sdcard present
else
//not present
and finally call the starting method.
Hope it helps.
Upload Image Application: It is working fine on emulator but unable to upload Image on test phone. It chooses pic from gallery but doesnt display anything in Imageview.
public class Uploadimage extends Activity {
public static int requestCode=1;
Button b1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadimage);
b1= (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, requestCode);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data) ;
if (requestCode==1 && resultCode==RESULT_OK) {
Uri image = data.getData();
String [] filepath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(image, filepath, null, null, null);
cursor.moveToFirst();
int column = cursor.getColumnIndex(filepath[0]);
String path= cursor.getString(column);
cursor.close();
ImageView imageview= (ImageView) findViewById(R.id.imageView1);
imageview.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
Use the following method for decoding your file path.
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 4;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bmp = BitmapFactory.decodeFile(filePath, o2); // this bmp object of Bitmap is global and you can set it to your ImageView.
}
Now you can call this function after this one
String path= cursor.getString(column);
decodeFile(path);
If your get the content from the mobile, below code must write in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
use this below code you will get the solutions..
`buttonLoadImage.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri targetUri = data.getData();
Bitmap bitmap;
try
{
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}`
I have an app, which has a button to select a photo from your gallery and it works fine and after selecting the image my app show came back to the activity and shows the image in an image View.
Every is working fine but sometimes ,when i select some particular images the preview is not showing. I have also tried to compress the image still its not working
My code is below..
In onCreate()
galeryBtn=(Button)findViewById(R.id.buttonGallery);
galeryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
In onActivityResult(int requestCode, int resultCode, Intent 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();
// String picturePath contains the path of selected Image
// Show the Selected Image on ImageView
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
Try like this
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = intent.getData();
try {
Bitmap bitmapImage =decodeBitmap(selectedImage );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Show the Selected Image on ImageView
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(bitmapImage);
}
And
public Bitmap decodeBitmap(Uri selectedImage) throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
I run into similar problems like getting cursor uri from resource, open stream, set bitmap etc. And it has bugs all the time.
So I searched libraries and found image-chooser-library library.
I bet you would like to try this project from image-chooser-library
It is very easy to use and solves all those nitty gritty problems for you, like images from picasa etc.
Hopefully it is useful for you.
The way you're trying to load a bitmap in onActivityResult() is not absolutely right. Sometimes you will not be able to open an image and your application can crash. You'd better use code like this:
Uri imageUri = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(imageUri);
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
} catch (FileNotFoundException e) {
// Handle the error
} finally {
if (imageStream != null) {
try {
imageStream.close();
} catch (IOException e) {
// Ignore the exception
}
}
}
Add this after imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageView.setImageURI(selectedImage);
It work for me.
I use below code to import an image from my Gallery to on my imageView. It is successful, but i want to resize the bitmap since app force close itself with heavy image imports.
String mPicPath1;
Button save;
ImageView logoview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);
mPicPath1 = null;
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewCard.this, Template.class);
if (!TextUtils.isEmpty(mPicPath1)) {
intent.putExtra("picture_path1", mPicPath1);
}
startActivity(intent);
}}
});
logoview=(ImageView)findViewById(R.id.logoview);
logoview.setScaleType(ScaleType.FIT_XY);
logoview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
openGallerylogo();
}
});
private void openGallerylogo() {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent data){
super.onActivityResult(requestCode, resultcode, data);
if (requestCode == 1)
{
if (data != null && 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]);
mPicPath1 = cursor.getString(columnIndex);
cursor.close();
logoview.setBackgroundResource(0);
logoview.setImageBitmap(BitmapFactory.decodeFile(mPicPath1));
}}
}
}
When i implement:
mPicPath1.setScaleType(ScaleType.FIT_XY);
Then i need to change mPicPath1 is from String to Bitmap. If i change then i have "The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments " error in this line:
logoview.setImageBitmap(BitmapFactory.decodeFile(mPicPath1));
Can you please correct my code above to import big size images and can pass it to SecondActivity. Thank you.
You should use this :
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 2048;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 3;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bmp = BitmapFactory.decodeFile(filePath, o2);
}
And call this function as:
decodeFile(mPicPath1 );
UPDATE:
You can use like in your code:
Make global Bitmap variable
Bitmap bmp ;
decodeFile(mPicPath1);
logoview.setImageBitmap(bmp);
Just go thorough with this to manage large bitmaps:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html