Force certain app to receive the intent (not chooser) [duplicate] - android

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.

Related

Pick any file using intent in android

I'm using following method to call pick any file but it doesn't work properly.
private void fileIntent(int file)
{
if ((ActivityCompat.checkSelfPermission(ICShowFileCabinetDetails.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, file);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), file);
}
}
Following permissions are set in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
OnActivtyresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_FILE && data != null) {
try {
mProPic = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
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);
// String filename = selectedImage.getLastPathSegment();
String[] filenames = picturePath.split("\\/");
int count = filenames.length;
String name = filenames[count - 1];
imagepickerselected = 1;
UploadIamgeinServer(1, name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Choose file getting open whenever i click to choose file in button click. But all files are shown like hidden except images, Click doest work. Without method in it button click works fine. If anyone found errors in code please let me know.
Thanks
try this code this my code only for .xls use yours.
or add read and write permission in manifest file
oncreate declare permission
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}
}
onclick of you button write this code
path= String.valueOf(Environment.getExternalStorageDirectory());
File file = new File(path);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.ms-excel");
try {
startActivityForResult(pdfOpenintent.createChooser(intent, "Select file"), 0); }
catch (ActivityNotFoundException e) {
}
onactivityresult yud get file path
public void onActivityResult(int requestCode, int resultCode, Intent result){
if (resultCode == RESULT_OK){
if (requestCode == 0) {
Uri data = result.getData();
else{
// CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");
Toast.makeText(Import_act.this,"Wrong File Selected ", Toast.LENGTH_SHORT).show();
}
}
}
}
I think you should add like this intent.addCategory(Intent.CATEGORY_OPENABLE);
. For more visit this link, Select File from file manager via Intent. I hope this may help you.

How to pick an image from gallery in samsung

I want to build an app can choose photo from the gallery. this is the code i use
Intent photo_pick = new Intent(Intent.ACTION_PICK);
photo_pick.setType("image/*");
startActivityForResult(photo_pick , PICK_PHOTO_INTENT );
this code i had try and it work on XiaoMi, Huawei phone. But when it work on samsung the path it return is the error path cannot to get the photo.
How to improve it to let the samsung phone also can work?
Check Below code for choose photo from the gallery,
private static final int REQUEST_PROFILE_ALBUM = 1;
Intent int_album = new Intent(Intent.ACTION_PICK);
int_album.setType("image/*");
int_album.putExtra(MediaStore.EXTRA_OUTPUT, img_url);
startActivityForResult(int_album, REQUEST_PROFILE_ALBUM);
After Select Image onActivityResult is called,
if (requestCode == REQUEST_PROFILE_ALBUM && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.getContentResolver().query(selectedImage, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String picturePath = cursor.getString(columnIndex);
}
Try this it may helps you:
Button btn_selectimage = (Button) findViewById(R.id.btn_selectimage);
btn_selectimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img_capture.setVisibility(View.VISIBLE);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
Code for xml:
<Button
android:id="#+id/btn_selectimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Picture"/>
Pick a image like this
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
Once you pick a image onActivityResult is called automatically
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
}
}
try this code:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (intent.resolveActivity(getPackageManager()) != null) {
// Bring up gallery to select a photo
startActivityForResult(intent, 2);
}else{
Toast.makeText(UserProfileActivity.this,"No Gallery app found!", Toast.LENGTH_SHORT).show();
}
In order to execute below code, you will require to get request persmission only if android version is higher then lolipop
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 500);

How to open gallery first instead of opening activity view?

So I'm trying to find a way how to write the code that when I open the app it automatically first of all open the gallery and then when you choose the picture it appears on Main Activity. How to do that? Am I need another activity? Because now first of all it opens Main Activity view and only then you can click the button and choose what you wanna do.
Code for loading and showing picture:
ocamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
} else if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Permission is important to be able edit photos.",
Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant
return;
}
#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 picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView im = (ImageView) findViewById(R.id.myimage);
im.setImageBitmap(BitmapFactory.decodeFile(picturePath));
BitmapDrawable abmp = (BitmapDrawable) im.getDrawable();
bmp = abmp.getBitmap();
if (picturePath != null && bmp != null) {
int height = bmp.getHeight(), width = bmp.getWidth();
if (height > 1280 && width > 960) {
Bitmap bmp = BitmapFactory.decodeFile(picturePath);
im.setImageBitmap(bmp);
im.setVisibility(View.VISIBLE);
} else {
im.setImageBitmap(bmp);
im.setVisibility(View.VISIBLE);
}
}
}
}
If you want your gallery code to run as the first thing, you can simply call the method inside onCreate of your activity
#Override
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
//you can check permissions here
//call the method here with code you use to open gallery
pickImageFromGallery();
}
private pickImageFromGallery(){
//your code to open gallery here
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
This will ensure your gallery is opened every time. You can optionally call the method inside onResume() because then you will be guaranteed that the code will run.
Good luck and I hope you find it helpful.

import images from gallery into fragment

im trying to implement a fragment inside a navigation slider. I need to create a button in 1 of my fragments to import images from my default gallery. I have tried many codes online, but they don't seem to be working.
It depend on android version you are using if you test your app in android 6.0 than you should ask permission at runtime else image is not returned by android.
For Pre-Marshmallow you can use code:
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent, 0);
and then override method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, requestCode, data);
try {
// When an Image is picked
if (requestCode == 0 && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
image.setImageBitmap(BitmapFactory.decodeFile(getRealPathFromURI(selectedImage)));
} else
new ShowErrorToast(getActivity(), "Hey! your Android phone is busy");
} catch (Exception e) {
}
}
than use method to get path of image
public String getRealPathFromURI(Uri data) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(data
, filePathColumn, null, null, null);
String picturePath = "";
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
return picturePath;
}
For Marshmallow you should ask for permission runtime and follow above code

Gallery intent.getData() returns null in onActivityResult

I recently fixed a known bug in my app that occurs on some devices; when the user takes a photo from an intent launched from my app, in the onActivityResult Uri uri = intent.getData(); returns null. I managed to fix that in the suggested manner. However I get the exact same issue when the user needs to Select a picture from his phone's photo gallery. The same intent.getData() == null.
Starting the intent:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
R.id.SELECT_IMAGE_ACTIVITY_REQUEST_CODE);
onActivityResult:
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();
dataHasChanged(ACTION_PICTURE, filePath);
PS: Strangely enough if I start the intent like shown below I can get the intent.getData() but only if I use the "Gallery" app on my samsung s4 and not the GooglePhotos app.
Intent pickImageIntent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (pickImageIntent.resolveActivity(getPackageManager()) != null)
startActivityForResult(pickImageIntent, R.id.SELECT_IMAGE_ACTIVITY_REQUEST_CODE);
I am unsure on how to proceed. I find the entire Android intents affair very confusing sometimes.
I'm giving you code for your reference:
Use following code after clicking pic from your app:
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,"Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
Below code will be in your onActivityResult():
if (requestCode == PICK_FROM_GALLERY) {
if (resultCode != RESULT_CANCELED) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
photo = extras2.getParcelable("data");
bitmap = photo;
profile_imageView.setImageBitmap(photo);
new ImageUploadTask().execute();
}
}
}
Hope this will solve your problem.
static final int REQUEST_GALLERY_IMAGE = 14;
----------
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_GALLERY_IMAGE );
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY_IMAGE && resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imagePreview.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Categories

Resources