Video capturing crash on Samsung android 5 with FileProvider - android

Model: Samsung SM-G900F (Android 5.0)
Code to launch camera:
File file = new File(getExternalFilesDir(null),"video.mp4");
Uri uri = FileProvider.getUriForFile(this, "example.com.myapplication.fileprovider", file);
final Intent takePictureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION| Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
final List<ResolveInfo> resInfoList =
getPackageManager()
.queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (final ResolveInfo resolveInfo : resInfoList) {
final String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(takePictureIntent, 42);
Log:
11-03 11:40:00.073 30377-30377/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sec.android.app.camera, PID: 30377
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2002, result=-1, data=Intent { act=inline-data dat=content://example.com.myapplication.fileprovider/external/Android/data/example.com.myapplication/files/video.mp4 (has extras) }} to activity {com.sec.android.app.camera/com.sec.android.app.camera.Camcorder}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3974)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4017)
at android.app.ActivityThread.access$1400(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1471)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetLong(Native Method)
at android.database.CursorWindow.getLong(CursorWindow.java:524)
at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:75)
at android.database.CursorWrapper.getLong(CursorWrapper.java:106)
at com.sec.android.app.camera.Camera.onActivityResult(Camera.java:6956)
at android.app.Activity.dispatchActivityResult(Activity.java:6475)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3970)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4017) 
at android.app.ActivityThread.access$1400(ActivityThread.java:172) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1471) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5832) 
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:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
 
Looks like video capturing works only with file uri and doesn't work with content uri.
Do you have the same issues? Could you suggest some general solution?

This helped me:
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", f);
} else {
uri = Uri.fromFile(f);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

This is working for me.
private void launchCamera() {
Intent captureVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (captureVideoIntent.resolveActivity(getPackageManager()) != null)
{
Uri videoUri = null;
try {
videoUri = getOutputMediaFileUri();
} catch (Exception ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (videoUri != null) {
captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(captureVideoIntent, REQUEST_CAMERA);
}
}
}
/**
* Creating file uri to store image/video
*/
private Uri getOutputMediaFileUri() {
if(Build.VERSION.SDK_INT >= 24) {
// For android N you need to use the file provider
return FileProvider.getUriForFile(this, getResources().getString(R.string.file_provider_name), getOutputMediaFile());
} else {
return Uri.fromFile(getOutputMediaFile());
}
}
/**
* returning file to store image / video
*/
private File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DirectoryNameWhereYouWantToStore");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".mp4");
}

Related

Trying to save image to gallery

I am new to Android development and are a bit stuck trying to save a image to the gallery. I have followed the guidelines on https://developer.android.com/training/camera/photobasics, and it works fine until I try to save the image to the gallery on the phone using getExternalStoragePublicDirectory.
When I use the getExternalFilesDir() all works, but when i try to use getExternalStoragePublicDirectory to get the picture to the gallery Ii got a NullPointerException.
I have added the WRITE_EXTERNAL_STORAGE permission to the manifest.
I have tried to read other posts about this, but havent found any soulutions to this problem.
Heres my code. If annyone culd help me finding out whats cousing the NullPointerException I would be thankful.
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
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(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
And heres my error in Logcat:
08-02 20:04:12.920 17455-17455/com.example.android.fishlist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.fishlist, PID: 17455
java.lang.NullPointerException
at java.io.File.<init>(File.java:282)
at com.example.android.fishlist.NewCatch.galleryAddPic(NewCatch.java:192)
at com.example.android.fishlist.NewCatch.access$200(NewCatch.java:45)
at com.example.android.fishlist.NewCatch$2.onClick(NewCatch.java:101)
at android.view.View.performClick(View.java:6891)
at android.widget.TextView.performClick(TextView.java:12651)
at android.view.View$PerformClick.run(View.java:26083)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

App is crashing when taken picture using ACTION_IMAGE_CAPTURE on some devices?

I have facing some strange behaviour with my Application : On Some device like samsung sony Onplus my application work fine but some device like
Lenovo a7000
redmi x
Application is crashing and I am getting this error
My code is :
private void captureImageFromCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoURI;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}
startActivityForResult(takePictureIntent, Constant.REQUEST_TAKE_PHOTO);
}
}
}
Here I am creating image file
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "IMAGE_" + timeStamp + "_";
// File storageDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES + "/PhotoGallery/");
File storageDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES );
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = image.getAbsolutePath();
Log.d("imageFileName", imageFileName);
Log.d("imageFile", image.toString());
return image;
}
This is my OnActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constant.REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
try {
setPic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And Here I am setting Pic by sending to another activity:
private void setPic() throws IOException {
Intent intent = new Intent(MainActivity.this, EditImageActivity.class);
intent.putExtra("mCurrentPhotoPath", compressImage(mCurrentPhotoPath,MainActivity.this));
intent.putExtra("CalledBy","Camera");
startActivity(intent);
}
There are another person who faced the same problem . Have the found the answer yet. I tired out a lot of question on stackoverflow but not of them work for me ,
Please let me know about this issue why in some devices is works fine and some devices that I mention above not,
Any Help is appreciated
I found two solution to your problem 1st One and 2nd One is below
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Create a File reference to access to future access
photoFile = getPhotoFileUri(photoFileName);
// wrap File object into a content provider
// required for API >= 24
// See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher
Uri fileProvider = FileProvider.getUriForFile(MyActivity.this, "com.codepath.fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(getPackageManager()) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
where
public File getPhotoFileUri(String fileName) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
File file = new File(mediaStorageDir.getPath() + File.separator + fileName);
return file;
}
I am also facing this problem. New devices require FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION and for devices with Api > 24 you have to implement provider

unfortunately camera has stopped working in Kitkat

I am trying to integrate taking a picture in Android. While running the application I am getting and error "Unfortunately, Camera has stopped", but my application didn't crash. I found this issue in Android "KITKAT". Here is the sample code I am using to take picture,
Using this function I am taking a picture,
private void take_picture_intent() {
Intent takePictureIntent = (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
? new Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE)
: new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this.getActivity(), "com.android.myapplication.fileprovider", photoFile);
Log.e(TAG, "photoFile: "+photoFile+" ,URI : "+photoURI.getPath());
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
getActivity().startActivityForResult(takePictureIntent, SelectMedia.IMAGE_CAPTURE_AT_THE_DOOR);
}
}
}
This function is used to generate Image path,
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (!storageDir.exists())
storageDir.mkdirs();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Here is the Log,
10-11 12:35:12.691 18815-18815/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sec.android.app.camera, PID: 18815
java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from
ProcessRecord{42d78c60 18815:com.sec.android.app.camera/u0a84} (pid=18815, uid=10084) that is not exported from uid 10786
at android.os.Parcel.readException(Parcel.java:1472)
at android.os.Parcel.readException(Parcel.java:1426)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:3201)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:4824)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2532)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1425)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:906)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:669)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:645)
at com.sec.android.app.camera.Camera$LastContentUriCallback.onCompleted(Camera.java:21369)
at com.sec.android.app.camera.Camera.onLaunchGalleryForImage(Camera.java:12409)
at com.sec.android.app.camera.Camera.onImageStoringCompleted(Camera.java:11140)
at com.sec.android.app.camera.CommonEngine.imageStoringCompleted(CommonEngine.java:6954)
at com.sec.android.app.camera.CeStateInitialized.handleMessage(CeStateInitialized.java:47)
at com.sec.android.app.camera.CommonEngine$StateMessageHandler.handleMessage(CommonEngine.java:957)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5590)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
10-11 12:35:13.021 600-19132/? E/android.os.Debug: !#Dumpstate > sdumpstate -k -t -z -d -m 18815 -o /data/log/dumpstate_app_error
I found this issue is due to conversion of URI. I have resolved this issue by replacing
FileProvider.getUriForFile(getApplicationContext(), "com.android.myapplication.fileprovider", photoFile);
By Adding a condition,
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT))
photoURI = FileProvider.getUriForFile(getApplicationContext(), "com.android.myapplication.fileprovider", photoFile);
else
photoURI = Uri.fromFile(photoFile);
on take_picture_intent() function.
Also In my Manifest I am have removed permission,
<uses-permission android:name="android.permission.CAMERA" />
Add the permission for pre-lollipop versions of specific package name, after that you can able to access it.
getApplicationContext().grantUriPermission(getCallingPackage(),
contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

Taking Photos Simply. onActivityResult null pointer

I have looked through here for help but nothing seems to be completely related or helped me fix the error I am facing. I copied everything from https://developer.android.com/training/camera/photobasics.html#TaskScalePhoto
How do I remove the null pointer from this line?
Bundle extras = data.getExtras();
The rest of the code is here.
#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);
}
//galleryAddPic();
}
//Creates Intent
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(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.joseph.webber.dartapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
//Creates File Path and Name
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Stacktrace
>06-04 01:28:39.945 20181-20181/com.joseph.webber.dartapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.joseph.webber.dartapp, PID: 20181
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.joseph.webber.dartapp/com.joseph.webber.dartapp.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4925)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4968)
at android.app.ActivityThread.access$1600(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1849)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.joseph.webber.dartapp.LoginActivity.onActivityResult(LoginActivity.java:98)
at android.app.Activity.dispatchActivityResult(Activity.java:7137)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4921)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:4968)
            at android.app.ActivityThread.access$1600(ActivityThread.java:222)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1849)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:158)
            at android.app.ActivityThread.main(ActivityThread.java:7229)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Null pointer Exception on file- URI?

In my app a capture button is there to capture an image using device camera,so I have used a method captureImage() on the click event of that button.When I click the button a null pointer exception is thrown.I could not understand how this happens Can anyone help? Thanks in advance!
capture button on on Create () method
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);*/
captureImage();
}
});
captureImage() method
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_REQUEST);
}
Null pointer exception on this method
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
Logcat
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:447)
at com.riafy.user.imagegallerydemo.MainActivity.getOutputMediaFileUri(MainActivity.java:235)
at com.riafy.user.imagegallerydemo.MainActivity.captureImage(MainActivity.java:97)
at com.riafy.user.imagegallerydemo.MainActivity.access$100(MainActivity.java:29)
at com.riafy.user.imagegallerydemo.MainActivity$2.onClick(MainActivity.java:68)
at android.view.View.performClick(View.java:4761)
at android.view.View$PerformClick.run(View.java:19767)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
getOutputMediaFile(type) returns null.
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
You are returning here:
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
Have you added the following permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
to your manifest?
My solution was simple.
Realised the error. Android Manifest had put a maxSDKVersion to 18 on the permission to write to storage. After removing that, it was working perfectly.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
I directly copied to code from Android getting started page. My problem was I was running it on emulator. Therefore I think the code above that I used could not assess my file system.
In my case, I found out SDK version 23 and up might need runtime permission for writing external storage. So I solved like this:
public Uri getOutputMediaFileUri(int type) {
requestRuntimePermission();
return Uri.fromFile(getOutputMediaFile(type));
}
public void requestRuntimePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(context,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
Note: You might put this instead of context and activity above if applicable

Categories

Resources