Open gallery app from Android Intent - java

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

selecting photos from google photos crushes my app

i'm writing an android app on java and need to let my users select and crop images from the gallery.
There is no problem when choosing an image from any native gallery, but when a user chooses to eater crop or choose an image from google photos app the app crushes.
I cannot figure out what is the source of the problem so any answer will be helpful
this is the code i'm using
class fields:
private Uri imageUri;
opening the camera:
private void camOpen() {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "file" + String.valueOf(System.currentTimeMillis()) + ".png");
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
imageUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_CODE);
}
opening the gallery:
private void galleryOpen() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(i, "select file"), SELECT_PHOTO_CODE);
}
cropping the image:
private void cropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", true);
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_CODE);
} catch (Exception e) {}
}
the result handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {
cropImage();
} else if (requestCode == SELECT_PHOTO_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
imageUri = data.getData();
cropImage();
}
} else if (requestCode == CROP_CODE && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
Bitmap b = bundle.getParcelable("data");
hasImageChanged=true;
ivProfilePic.setImageBitmap(b);
capturedImage = b;
}
}
thank you for any useful help...
Android does not support crop intent because croping is not part of android api.
So i recommend you for Using library
the issue was with the crop intent. I ended up using the uCrop library and it fixed the problem.

Android Intent image picker from gallary... Why can't show in some devices.?

Why choose a picture from the gallery by >>Intent<< > can't show in some devices. I'm Thai ,Sorry for my language ...Thank U
public void click(View v){
intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "select??"), 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK&&requestCode == 1) {
Uri uri = Uri.parse(get_Path(data.getData()));
//--I use This >>uri<< for setImage ....But cant't show in some devices.?
}
}
public String get_Path(Uri uri) {
String path = ""; ///////////////
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
path = uri.getPath();
} else {
cursor.moveToFirst();
int num = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(num);
cursor.close();
}
return path;
}
Beginning in Android 6.0 or >7 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
read about this
and follow this link of my ans my question how to ask runtime permssion

Android Program Crashing NullPoint Exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hey so I have been trying to fix this problem for a couple of hours and checked a lot of the other questions extensively in an attempt to remedy this problem.
So in my Main Activity I have two activities that both either grabs an image from the gallery or is a photo depending on the button
public void DoTakePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, TAKE_PICTURE);
}
}
public void DoShowSelectImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
So I know the problem likes on my onActivityResult where the data seems to be null I tried using the super so it gets back the lost activity or checking to see if data is
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE || requestCode == TAKE_PICTURE && null != data) {
if (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]);
mImageFullPathAndName = cursor.getString(columnIndex);
cursor.close();
jobID = "";
File file = new File(mImageFullPathAndName);
Bitmap mCurrentSelectedBitmap = decodeFile(file);
if (mCurrentSelectedBitmap != null) {
ivSelectedImg.setImageBitmap(mCurrentSelectedBitmap);
int w = mCurrentSelectedBitmap.getWidth();
int h = mCurrentSelectedBitmap.getHeight();
int length = (w > h) ? w : h;
if (length > OPTIMIZED_LENGTH) {
float ratio = (float) w / h;
int newW, newH = 0;
if (ratio > 1.0) {
newW = OPTIMIZED_LENGTH;
newH = (int) (OPTIMIZED_LENGTH / ratio);
} else {
newH = OPTIMIZED_LENGTH;
newW = (int) (OPTIMIZED_LENGTH * ratio);
}
mCurrentSelectedBitmap = rescaleBitmap(mCurrentSelectedBitmap, newW, newH);
}
mImageFullPathAndName = SaveImage(mCurrentSelectedBitmap);
}
}
}
}
So my Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.zola.capchem/com.example.zola.capchem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
I have tried most of the things on this site but the app still ends up crashing. No clue what to do here.
Your code would crash if you try to take a picture from the camera.
The method for taking a photo via camera and obtaining a photo from the gallery/file system is quite different.
For doing both, you fire an intent with an ACTION and some extras. You launch an activity for a result with this intent. The result is returned to you in onActivityResult() via the intent passed to it.
However, the result stored in the returned intent is different for both cases.
1) Taking a photo through camera: The bitmap itself of the image taken is returned to you, as an extra in the intent bundle. You can access it as:
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
//use bitmap however you like...
2) Select a photo from gallery: You may or may not get a URI of the selected image (via data.getUri()). In case you get an URI, you can obtain your image through that URI. However, this uri may be null sometimes, in which case the android system has chosen to write the image on to the image URI that you had passed as an intent extra while launching the activity for result.
Hence, first, define a temporary URI and use it to launch the activity to select image from gallery:
private URI getTempFile()
{
if (isExternalStorageWritable())
{
File file = new File(Environment.getExternalStorageDirectory(), "temporary_file.jpg");
try
{
if(!file.exists())
{
file.createNewFile();
}
} catch (IOException e)
{
}
return Uri.fromFile(file);
} else
{
return null;
}
}
public void DoShowSelectImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
startActivityForResult(i, SELECT_PICTURE);
}
and inside your onActivityResult:
Uri selectedimage = data.getData();
if(selectedimage == null)
{
selectedimage = getTempFile();
}
You need to handle both these cases seperately in your onActivityResult:
if(result == RESULT_OK && data != null)
{
Bitmap mCurrentSelectedBitmap;
if(requestCode == SELECT_PICTURE)
{
Uri selectedimage = data.getData();
if(selectedimage == null)
{
selectedimage = getTempFile();
}
......
......
mCurrentSelectedBitmap = decodeFile(file);
}
else if(requestCode == TAKE_PICTURE)
{
Bundle extras = data.getExtras();
mCurrentSelectedBitmap = (Bitmap) extras.get("data");
}
.......
.......
//Do your thing
}
NOTE: you might need to add permission in your manifest to write to external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()'

I am Trying To upload image to server from gallery and camera.When i Choose image from gallery to upload to server its Work Perfactly.But when i Select camera captured Image for upload to server Its Crash And Showing the error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
At OnActivityResult.
#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 };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
decodeFile(picturePath);
new ImageUploadTask().execute();
}else {
Toast.makeText(getApplicationContext(), "User Canceled",
Toast.LENGTH_LONG).show();
}
}
i got the error on this line in onActivityResult
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
The method i used for open camera on button click.
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Info.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
}
})
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Help Me solve this problem.I don't know How t get this error even after i used is already in my Previous PROJECT.
THANKS in Advance
I had same issue when working with Camera api and Intent of onActivityResult, finally I found out it depends on your android device version, in Android M (Marshmallow - 6.0–6.0.1 ) onActivityResult intent is like below :
requestCode : 230 resultCode : -1 intent :Intent{dat=file:///storage/emulated/0/Pictures/Rahnama/IMG_20160508_121332_1519065 564.jpg typ=image/jpeg } RESULT_OK : -1
and for android versions lower than Marshmallow:
requestCode : 230 resultCode : -1 intent : Intent { dat=content://media/external/images/media/309 (has extras) } RESULT_OK : -1
I think you must check android version onActivityResult and the for android versions Marshmallow to get direct file from path in the Uri and Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M){
final Uri data = intent.getData();
final File file = new File(data.getPath());
// now you can upload your image file
}else{
// in android version lower than M your method must work
}
I hope it can be useful for you.
if (null != account.getPhotoUrl()) {
// Write code here
}
I meet this problem either, after many test, I found its because I set the attribute named android:windowIsTranslucent=true, if I delete this attribute from style, it always work.

Android Launching Camera Intent from Fragment

I currently have an activity that hosts multiple fragments and I am on my third fragment of a collection.
In that fragment I use an Intent to launch either the Camera or Gallery. See code:
public Intent getImageIntent() {
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
// Calling activity should exeecute:
// startActivityForResult(chooserIntent, 1);
return chooserIntent;
}
After that the onActivityResult executes:
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mProductBitmap = (Bitmap) extras.get("data");
imgProduct.setImageBitmap(mProductBitmap);
}
Where mProductBitmap is a Bitmap Global Variable and imgProduct is an ImageView already initialized.
For some reason, first: The Camera option force closes the app, and gets a null pointer from the actual fragment itself, like the fragment items are all null again.
Second: The gallery options (More then one) don't error out but don't show the image either.
Any help would be appreciated. I've looked at every response possible, but not many people call an intent from a fragment that isn't the initial fragment that the activity is hosting.
Thanks!
EDIT:
Found out sometimes my Context is Null after the onActivityResult. If anyone has encountered this help is appreciated. Thanks.
EDIT: Below is by onActivityResult method, most of the time the first if should be executed.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
handleSmallCameraPhoto(intent);
} else {
if (requestCode == 1) {
InputStream stream = null;
if (intent == null) {
System.out.println("DATA IS NULL..");
} else {
try {
if (mProductBitmap != null) {
mProductBitmap.recycle();
}
stream = getActivity().getContentResolver().openInputStream(
intent.getData());
mProductBitmap = BitmapFactory.decodeStream(stream);
System.out.println(mProductBitmap);
System.out.println("Setting image result");
imgProduct.setImageBitmap(mProductBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
}
}
Your photo is saved in PATH_TO_SAVE location.
You should in onActivityResult do something like this:
File file = new File(PATH_TO_SAVE);
Bitmap bmp = BitmapFactory.decodeFile(file.getPath());

Categories