This show the box with the applications to choose an image or take a picture with camera. If I select Camera this let me to take a picture but there is no return or save option. I updated my answer posting the activity result code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
Log.e("TAG", "Only called when a image from gallery is selected");
}
else
{
Log.e("TAG", "Data is null");
}
break;
}
}
private void ChooseImage()
{
// Create gallery intent
Intent _intentGallery = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
_intentGallery.setAction(Intent.ACTION_PICK);
_intentGallery.putExtra("return-data", true);
// startActivityForResult(_intentGallery, 1);
// Create camera intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Create chooser
Intent chooser = Intent.createChooser(galleryIntent, getString(R.string.choose_an_application));
// Create list of gallery intents
List<Intent> galleryIntents = new ArrayList<Intent>();
// Add intents to list
PackageManager pm = getApplicationContext().getPackageManager();
for (ResolveInfo ri: pm.queryIntentActivities(_intentGallery, PackageManager.MATCH_DEFAULT_ONLY))
{
Intent intent = pm.getLaunchIntentForPackage(ri.activityInfo.packageName);
intent.setAction(Intent.ACTION_PICK);
intent.putExtra("return-data", true);
galleryIntents.add(intent);
}
// Show dialog
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, galleryIntents.toArray(new Parcelable[] {}));
startActivityForResult(chooser, 1);
}
Manifest permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
You have to implement onActivityResult. Then you can get data.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
In this case, REQUEST_IMAGE_CAPTURE is 1 as you defined it, so change it to 1.
Don't forget the manifest rule uses-feature.
See more: https://developer.android.com/training/camera/photobasics.html
Related
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)
I'm having a certain problem when playing an mp3 file specified by the user with MediaPlayer.
try {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), audio);
mPlayer.prepare();
mPlayer.start(); }
catch (IOException e) {
numberText.setText("IO EXCEPTION");
e.printStackTrace();
}
the problem is in mPlayer.setDataSource(getApplicationContext(), audio)
Here I get the specified mp3 from the user
setAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
audioPath = intent.getData().getPath();
audio = Uri.parse(audioPath);
}
}
}
});
The error log shows this
setDataSource: SecurityException! uri=content://com.android.providers.downloads.documents/document/1545
java.lang.SecurityException: Permission Denial: opening provider com.android.providers.downloads.DownloadStorageProvider from ProcessRecord{7b8354b 23595:com.example.m1tr0s0ul4s.thatawkwardcall/u0a137} (pid=23595, uid=10137) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
at android.os.Parcel.readException(Parcel.java:1540)
at android.os.Parcel.readException(Parcel.java:1493)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:3372)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:4819)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2527)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1486)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1092)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:932)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:859)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:987)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:961)
at com.example.m1tr0s0ul4s.thatawkwardcall.AcceptCall.onCreate(AcceptCall.java:55)
at android.app.Activity.performCreate(Activity.java:5966)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
10-20 17:31:13.041 23595-23595/com.example.m1tr0s0ul4s.thatawkwardcall
E/MediaPlayer: Unable to create media player
I have literally no idea what is going on :/ please help
In case you are already requesting for Runtime Permissions try this code:
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
If you're not then you must check for Runtime Permissions in Marshmallow and above.
Add this code to your Manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Now in your onClick of setAudio you need to check if the user has given you permissions to access the storage of the device
setAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 11);
} else {
//You already have the permission, just go ahead.
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
}
}
When you request permission the user action is returned in onRequestPermissionResult(..). Here's how you could handle the user action.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 11) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//The External Storage READ Permission is granted to you... Continue your left job...
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
} else{
//permission denied
}
}
audioPath = intent.getData().getPath();
audio = Uri.parse(audioPath);
intent.getData() already returns an Uri object, so you're potentially throwing away data required to read the specific file like the scheme, host or query properties.
I'm trying to take a picture with the back camera and then get it's bytes in a serice I am using this code:
Camera camera = Camera.open();
SurfaceView view = new SurfaceView(getApplicationContext());
SurfaceHolder holder = view.getHolder();
camera.getParameters().setPreviewSize(1, 1);
camera.setPreviewDisplay(holder);
camera.startPreview();
camera.takePicture(null, pictureCallback, null);
But it is not working. I am not getting an exception but pictureCallback is never being called.
Taken from the android docs: http://developer.android.com/training/camera/photobasics.html
You should call the camera intent like this:
First add the necessary permissions to your app in the androidmanifest file:
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
After that call the corresponding intent to start the camera:
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
The data you receive from the camera will be called in the following method, where you will be able to store or use it as you wish:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
In case you want to implement this in a service, taking the code from this link, you should be able to take a picture from a service:
mPreview = new CameraPreview(this, mCamera, jpegCallback);
WindowManager wm = (WindowManager) this
.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSPARENT);
params.height = 1;
params.width = 1;
wm.addView(mPreview, params);
As stated by the comments, please note that this needs the permission SYSTEM_ALERT_WINDOW to work, users might not want to allow an App to use this permission.
I am trying to pick picture of my gallery I can access my Gallery but after clicking the image the app crashed.
I try to debug it and it crashed in the onActivityResult method at this line InputStream openInputStream = getContentResolver().openInputStream(photoLocation);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY) {
Uri photoLocation = data.getData();
try {
InputStream openInputStream = getContentResolver().openInputStream(photoLocation);
selectedImage = BitmapFactory.decodeStream(openInputStream);
imagePlantsearch.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image",Toast.LENGTH_LONG).show();
}
}
}
}
You forgot to write permission for reading files from device. Just add below line to your AndroidManifest.xml file.
Add Read Permission to Manifest File.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If you have read your error carefully. It was already suggested by it to add permission to Manifest file.
insert permission first in your manifest and then add following code..
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
add this code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
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.