How to Detect the photo or video selection from library - java

I am using the Below Code for get the image and video from gallery, but can't Detect the photo or video selection from library
Intent intent = new Intent();
intent.setType("video/*,image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_VIDEO);

Did you used onActivityResult to get the selected image ? code will be like below.
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
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); // file path of selected image
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
yourimgView.setImageBitmap(yourSelectedImage);
}
}
}
For intent you can try with this.
final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);

Related

App exits after selecting image in Android Studio (OnActivityResult not called)

So I used this to open my image choose upon button click
//Open image chooser
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
and used onActivityResult
private final static int SELECT_PHOTO = 12345;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("CALLED", "OnActivity Result");
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
Log.e("img", "It worked");
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
In logcat, OnactivityResult is not being called, and I cant figure out why. So when I click the button, the image chooser pops up, I choose an image, and then it exits back to the main screen.
Am I missing something, as I've followed others' code but I still get the same thing
Give this a try:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Select:"), SELECT_PHOTO);

Sending an email + attachment from an custom app in Android Studio, why is the URI null?

Hello
I am working on an app that can send an email with an attachment.
I am completly stuck. I am unable to attach an attachment to my app.
I press the attachment button and I can choose a picture but every time I press the picture, the app crash.
The LogCat gives me a NullPointerException and saying the problem is at "Log.e("Attachment Path: ", attachmentFile);" so my guess is that something goes wrong when I try to save it since the attachmentFile is null.
I can not figure out why the attachmentFile is null since that is the reason I get NullPointerException.
I appreciate every help I can get.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null,null,null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
attachmentFile = cursor.getString(columnIndex);
Log.e("Attachment Path: ", attachmentFile);
URI = Uri.parse("file://" + attachmentFile);
cursor.close();
}
}
Here is the crash
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=101, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:39 flg=0x1 }} to activity {com.example.william.mailappen/com.example.william.mailappen.MainMail}: java.lang.NullPointerException: println needs a message
UPDATE
I use this method to open the picture gallery
public void pictureGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
2:nd UPDATE
Dont know if I am doing it correctly or if this is the right way to go compared to the other method above or is it something super clear that I am missing? The URI is still null...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK)
{
File filelocation = new File(Environment.getExternalStorageDirectory(), "picture.jpg");
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("image/*");
String to[] = {mailAdressTextField.getText().toString()};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, messageTextField.getText().toString());
}
I used something like this. Forked fine
File filelocation = new File(Environment.getExternalStorageDirectory(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {"email#email.com"};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your string");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
EDIT
filename is the name of your file with postfix (for example .jpg)

Retrieving picture from Sharedpreferences path

In the app I am building, the user selects a picture from gallery and the path is saved in Shared Preferences. I then want to retrieve this picture from the stored path but it doesn't work. The image is an ImageButton, which the user clicks in order to select picture from Gallery.
The code I have to retrieve the picture and "put" on the ImageButton is:
This code does actually work now, put it here in case it helps others.
File imgFile = new File(sharedpreferences.getString(Path, LOCATION_SERVICE));
if(imgFile.exists())
{
Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageButton img=(ImageButton)findViewById(R.id.AddPic);
img.setImageBitmap(b);
}
I know the path is correct, but I am not able to retrieve the picture and put it on the ImageButton.
Below is the code where the user clicks on the ImageButton, and selects a picture from the gallery and the path of that picture is stored within the sharedPreferences:
imgButton = (ImageButton) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(GaleryIntent, 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 SelectedCursor = getContentResolver().query(SelectedImage, FilePathColumn, null, null, null);
SelectedCursor.moveToFirst();
int columnIndex = SelectedCursor.getColumnIndex(FilePathColumn[0]);
String picturePath = SelectedCursor.getString(columnIndex);
SelectedCursor.close();
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Editor editor = sharedpreferences.edit();
editor.putString(Path, picturePath);
editor.commit();
}
}
What am I doing wrong?
Thanks very much!

Android: App crashes when selecting image from Samsung gallery (but it works with Google Photo app)

Good day,
The following code works when I select an image from the Google Photo app. However, when I select the same image from Samsung stock gallery, my app crashes.
I did some troubleshooting and realize the problem is with the getContentResolver().query():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
//Error happens when program try to run the following line of code
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Toast.makeText(getApplicationContext(), picturePath, Toast.LENGTH_LONG).show();
}
}
Please help me. Thank you.

Open gallery app from Android Intent

I'm looking for a way to open the Android gallery application from an intent.
I do not want to return a picture, but rather just open the gallery to allow the user to use it as if they selected it from the launcher (View pictures/folders).
I have tried to do the following:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
However this is causing the application to close once I select a picture (I know this is because of the ACTION_GET_CONTENT), but I need to just open the gallery.
Any help would be great.
Thanks
This is what you need:
ACTION_VIEW
Change your code to:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I hope this will help you. This code works for me.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
ResultCode is used for updating the selected image to Gallery View
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);
if (cursor == null || cursor.getCount() < 1) {
return; // no cursor or no record. DO YOUR ERROR HANDLING
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) // no column index
return; // DO YOUR ERROR HANDLING
String picturePath = cursor.getString(columnIndex);
cursor.close(); // close cursor
photo = decodeFilePath(picturePath.toString());
List<Bitmap> bitmap = new ArrayList<Bitmap>();
bitmap.add(photo);
ImageAdapter imageAdapter = new ImageAdapter(
AddIncidentScreen.this, bitmap);
imageAdapter.notifyDataSetChanged();
newTagImage.setAdapter(imageAdapter);
}
You can open gallery using following intent:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Tested on Android 4.0+
Following can be used in Activity or Fragment.
private File mCurrentPhoto;
Add permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
Add Intents to open "image-selector" and "photo-capture"
//A system-based view to select photos.
private void dispatchPhotoSelectionIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.startActivityForResult(galleryIntent, REQUEST_IMAGE_SELECTOR);
}
//Open system camera application to capture a photo.
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(App.Instance.getPackageManager()) != null) {
try {
createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (mCurrentPhoto != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Add handling when getting photo.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE_SELECTOR:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = App.Instance.getContentResolver().query(data.getData(), filePathColumn, null, null, null);
if (cursor == null || cursor.getCount() < 1) {
mCurrentPhoto = null;
break;
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) { // no column index
mCurrentPhoto = null;
break;
}
mCurrentPhoto = new File(cursor.getString(columnIndex));
cursor.close();
} else {
mCurrentPhoto = null;
}
break;
case REQUEST_IMAGE_CAPTURE:
if (resultCode != Activity.RESULT_OK) {
mCurrentPhoto = null;
}
break;
}
if (mCurrentPhoto != null) {
ImageView imageView = (ImageView) [parent].findViewById(R.id.loaded_iv);
Picasso.with(App.Instance).load(mCurrentPhoto).into(imageView);
}
super.onActivityResult(requestCode, resultCode, data);
}
As you don't want a result to return, try following simple code.
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivity(i);
if somebody still getting the error, even after adding the following code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
then you might be opening the intent in another class (by calling) due to this the app will crash when you click the button.
SOLUTION FOR THE PROBLEM
Put intent in the class file which is connected to the button's layout file.
for example- activity_main.xml contains the button and it is connected to MainActivity.java file. but due to fragmentation, you are defining the intent in some other class(lets says Activity.java) then your app will crash unless you place the intent in MainActivity.java file. I was getting this error and it is resolved by this.

Categories