ImageView doesn't show image from intent in java android - java

I've tried a couple different ways to show a chosen image from the gallery in a imageView. In the MainActivity I let the user choose an Image from Gallery and use an intent in the MainActivity, to send the uri of the image to the NextActivity and set the uri to the imageView, but it's not working. I can't see the Image. In the debug mode I see the uri in the variable which I set to the ImageView but it doesn't show the image.
My code
MainActivity.java onCreate method
<!-- language: java -->
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
Intent intent = new Intent (this, NextActivity.class );
if(imageUri != null){
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
}
}
NextActivity.java onCreate method
<!-- language: java -->
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
Intent intent = getIntent();
String image_path = intent.getStringExtra("imageUri");
Uri fileUri = Uri.parse(image_path);
imgView.setImageURI(fileUri);
I've tried to send the Uri as it is with intent, converted as a String and reconverted and so on. I don't know.
NextActivity XML
<!-- language: xml -->
<ImageView
android:id="#+id/imageView1"
android:layout_width="396dp"
android:layout_height="450dp"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.466"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Try this:
Uri fileUri = Uri.parse(image_path);
imgView.setImageURI(null);
imgView.setImageURI(fileUri);

Ideally, this would be just one activity (perhaps using two fragments), rather than two activities.
But, if you want to stick with this structure, you will need to change this:
imageUri = data.getData();
Intent intent = new Intent (this, NextActivity.class );
if(imageUri != null){
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
}
to:
imageUri = data.getData();
if (imageUri != null){
Intent intent = new Intent (this, NextActivity.class);
intent.setData(imageUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
and change:
String image_path = intent.getStringExtra("imageUri");
Uri fileUri = Uri.parse(image_path);
to:
Uri fileUri = intent.getData();
Without that, NextActivity will not have rights to use the content identified by the Uri.
Also, please replace setImageURI() with an image-loading library, such as Glide or Picasso.

Related

Custom Gallery Image Picker

I would like to allow the user to pock only one image that can be referenced via a uri, I've successfully done this through the following code:
private static final int PICK_IMAGE_REQUEST = 1;
private Uri imageUri;
// Choose file extended from BottomTabView, opens all images on device
public static void openFileChooser(Context context) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(intent, PICK_IMAGE_REQUEST);
// Slide Animation
((Activity) context).overridePendingTransition(R.anim.slide_in_up, R.anim.nothing);
}
// TODO: Is it better to use bitmap or URI
// Check if user has selected file and describe next step
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
// Retrieve image as a URI
imageUri = data.getData();
// Pass image URI to an intent and start activity
Intent intent = new Intent(this, UploadImageActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
// Slide Animation
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
this.finish();
}
}
The above code opens the following:
However, I would like to have something like the following:
Question: How can I achieve something more like the "Custom Gallery"?
if you want to custom layout pick image, you need:
create a screen and using recyclerView to make the layout as you want
get all picture gallery (https://stackoverflow.com/a/25957752/10153377)

pick a picture from gallery, after pic image i want to show it on different page

I got a code for pick a picture from my device gallery , code is like this i used.
Intent getintent = new Intent(Intent.ACTION_GET_CONTENT);
getintent.setType("image/*");
Intent pickintent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickintent.setType("image/*");
Intent chooserintent = Intent.createChooser(getintent, "Select Image");
chooserintent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickintent});
startActivityForResult(chooserintent, SELECT_PICTURE);
chooserintent.putExtra("data", SELECT_PICTURE);
Can i put a picture as a extra to send it to another intent? this is my code for 2nd page to show the picture that i choose in 1st Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showpic2);
findViewById(R.id.imageButton); // Replace with id of your button.
Intent intent = getIntent();
Bitmap gambar = intent.getData("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(gambar);
}
I am getting error with this code, can someone help me? thanks guys !!
sorry for my bad english.
You don't need to put the actual image's bitmap into an intent. After coming back from gallery you will be given an Uri. This uri points to the selected image. To display this image on another activity, what you should do is to only pass that Uri to the second activity.
First Activity's onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_ID && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra("imageUri", uri);
startActivity(intent);
}
}
And in the second Activity's onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showpic2);
Uri uri = intent.getParcelableExtra("imageUri");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageUri(uri);
}

Activity results always returns null when asking for picture

I'm trying to get image from the camera or the gallery (whatever the user chose) in one intent. the problem is that I always get intent.getData() as null in OnActivityResult.
I'm doing the following as suggested here:
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent });
startActivityForResult(chooserIntent, SELECT_PICTURE);
OnActivityResult:
if (requestCode == SELECT_PICTURE && resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
final Uri imageUri = data.getData();
Log.e("uri", imageUri + "");
uri is null
Well, ACTION_IMAGE_CAPTURE does not return Uri.
But if by any chance you really want to get the Uri after taking a photo by using it, then you need to specify the path for the picture (it will save the photo on that path, so it's not temporary).
This is one of that example (this will create directory & prepare the new file for your image):
// Determine Uri of camera image to save.
File root = new File(
Environment.getExternalStorageDirectory() + File.separator + locationName + File.separator);
root.mkdirs();
String fname = imagePrefixName + System.currentTimeMillis() + ".jpg";
File imageMainDirectory = new File(root, fname);
Uri outputFileUri = Uri.fromFile(imageMainDirectory); //make sure you store this in the place that can be accessed from your onActivityResult
After you decided your outputUri & store it, then you need to implement that uri on your camera intent like this:
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
Then, when you received the data you can do this to check if the picture is come from gallery or camera (picture that stored has Uri on it):
final Uri imageUri = data.getData();
if (imageUri == null)
{
imageUri = outputFileUri;
}
Make sure you implement the permission for write & read external storage & with this, i think you will get Uri that you want.

How to transfer a Uri image from one activity to another?

In my app I need to transfer a Uri image from my first Activity to another. I know how to send a Bitmap through an intent. I'm a bigginer programmer so I don't know what would be better to do: transfer the Uri with an intent or change the Uri to a Bitmap then send that?
use with putExtra to send the Uri Path:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent .setClass(ThisActivity.this, NewActivity.class);
intent .putExtra("KEY", Uri);
startActivity(intent );
In the newActivity OnCreate method:
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("KEY")) {
Uri= extras.getString("KEY");
}
Use those func:
Uri to String:
Uri uri;
String stringUri;
stringUri = uri.toString();
String to Uri:
Uri uri;
String stringUri;
uri = Uri.parse(stringUri);
To avoid the error you are getting, in the code given by Miki franko, replace the line :
Uri= extras.getString("KEY");
with :
uri= Uri.parse(extras.getString("KEY"));
This is just to make the code work as I think you didn't understand what Miki tried to explain through the code.
Keep us posted if you get it resolved now.
//First Activity to get a Uri
String uri_Str = Uri.toString();
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent .putExtra("uri_Str", uri_Str);
startActivity(intent);
//Second Activity get a Uri path
Bundle b = getIntent().getExtras();
if (b != null) {
String uri_Str= b.getString("uri_Str");
Uri uri = Uri.parse(uri_Str);
}
First Activity
Uri uri = data.getData();
Intent intent=new Intent(Firstclass.class,secondclass.class);
intent.putExtra("imageUri", uri.toString());
startActivity(intent);
Second class
Imageview iv_photo=(ImageView)findViewById(R.id.iv_photo);
Bundle extras = getIntent().getExtras();
myUri = Uri.parse(extras.getString("imageUri"));
iv_photo.setImageURI(myUri);
In your first class, you can pass the image uri like this:
Intent intent = new Intent();
intent.putExtra("your_key", imageUri.toString());
startActivity(intent);
And in the second or receiver activity, you can access the image uri this way:
Bundle extras = getIntent().getExtras();
if(extras != null){
Uri imageUri = Uri.parse(extras.getString("your_key"));
}

How to pass a URI to an intent?

I'm trying to pass a URI-Object to my Intent in order to use that URI
in another activity.
How do I pass a URI?
private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra("imageUri", imageUri);
startActivity(intent);
this.finish();
How do I use now this URI in my other activity?
imageUri = extras.getString("imageUri"); // I know thats wrong ...
you can store the uri as string
intent.putExtra("imageUri", imageUri.toString());
and then just convert the string back to uri like this
Uri myUri = Uri.parse(extras.getString("imageUri"));
The Uri class implements Parcelable, so you can add and extract it directly from the Intent
// Add a Uri instance to an Intent
intent.putExtra("imageUri", uri);
// Get a Uri from an Intent
Uri uri = intent.getParcelableExtra("imageUri");
You can use the same method for any objects that implement Parcelable, and you can implement Parcelable on your own objects if required.
In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.
Look at this simple approach.
// put uri to intent
intent.setData(imageUri);
And to get Uri back from intent:
// Get Uri from Intent
Uri imageUri=getIntent().getData();
private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
this.finish();
And then you can fetch it like this:
imageUri = Uri.parse(extras.getString("imageUri"));
here how I use it;
This button inside my CameraActionActivity Activity class where I call camera
btn_frag_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intenImatToSec = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intenImatToSec, REQUEST_CODE_VIDEO);
//intenImatToSec.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//intenImatToSec.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//Toast.makeText(getActivity(), "Hello From Camera", Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_IMG) {
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
Intent intentBitMap = new Intent(getActivity(), DisplayImage.class);
// aldıgımız imagi burda yonlendirdiğimiz sınıfa iletiyoruz
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intentBitMap.putExtra("byteArray", _bs.toByteArray());
startActivity(intentBitMap);
} else if (requestCode == REQUEST_CODE_VIDEO) {
Uri videoUrl = data.getData();
Intent intenToDisplayVideo = new Intent(getActivity(), DisplayVideo.class);
intenToDisplayVideo.putExtra("videoUri", videoUrl.toString());
startActivity(intenToDisplayVideo);
}
}
}
And my other DisplayVideo Activity Class
VideoView videoView = (VideoView) findViewById(R.id.videoview_display_video_actvity);
Bundle extras = getIntent().getExtras();
Uri myUri= Uri.parse(extras.getString("videoUri"));
videoView.setVideoURI(myUri);
If you want to use standard extra data field, you would do something like this:
private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra(Intent.EXTRA_STREAM, imageUri.toString());
startActivity(intent);
this.finish();
The documentation for Intent says:
EXTRA_STREAM added in API level 1
String EXTRA_STREAM
A content: URI holding a stream of data associated with the Intent,
used with ACTION_SEND to supply the data being sent.
Constant Value: "android.intent.extra.STREAM"
You don't have to use the built-in standard names, but it's probably good practice and more reusable. Take a look at the developer documentation for a list of all the built-in standard extra data fields.
The Uri.parse(extras.getString("imageUri")) was causing an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference
So I changed to the following:
intent.putExtra("imageUri", imageUri)
and
Uri uri = (Uri) getIntent().get("imageUri");
This solved the problem.
you can do like this. imageuri can be converted into string like this.
intent.putExtra("imageUri", imageUri.toString());

Categories