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
Related
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
I have a permission exception when I try (I think) to create a file in my physical device's external storage (nexus 5 android 6.0), whereas it works fine with a 4.3 emulated device.
My permissions are fine, but I get this error :
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.VIDEO_CAPTURE flg=0x3 cmp=com.google.android.GoogleCamera/com.android.camera.VideoCamera clip={text/uri-list U:file:///storage/emulated/0/Pictures/MyCameraApp/VID_20151216_145322.mp4} (has extras) } from ProcessRecord{5dab894 22712:com.***} (pid=22712, uid=10199) with revoked permission android.permission.CAMERA
any idea ?
I'll add a little more information :
My media utils is basic copy/paste from google video tutorial :
public class MediaUtils {
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
public static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
public static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File
.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
And my intent :
Uri fileUri = MediaUtils.getOutputMediaFileUri(MediaUtils.MEDIA_TYPE_VIDEO);
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
There is a new permission system on API 23 and higher.
The permission is requested at run time.
You should read this How to manage permission on Android 6.0 and this Android request permission
I can press a button, open up the native camera app, and successfully take a picture. But then when I check the Gallery or Photos native apps on my phone, the picture isn't saved there. I'm very new to Android so it's likely I'm missing something important in my code.
Questions:
1) Where are these pictures being saved?
2) Can I modify the below code somehow to save instead to internal storage, so all pictures taken with my app are private and only accessible through my app?
3) If I wanted to save these pictures to an object, along with some text/other input, what would be the best way? Should I just save a Uri or some identifier to reference the image later, or save the actual BitMap image?
Any help is greatly appreciated, thanks!
Here is my code to take the picture:
mImageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE);
}
}
CameraUtils class taken straight from Google developer guides:
public static Uri getOutputMediaFileUri(int type)
{
return Uri.fromFile(getOutputMediaFile(type));
}
public static File getOutputMediaFile(int type)
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "camera");
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs())
{
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
}
else if(type == MEDIA_TYPE_VIDEO)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
}
else
{
return null;
}
return mediaFile;
}
1) By looking at the code, I'd expect the pictures to be saved in a directory called 'camera' which would be found in the Pictures folder on your device (external storage). These might not instantly appear in your gallery, however in later versions of Android (Kitkat and maybe jelly-bean though I can't verify that right now) you should be able to open the Photos app and find them somewhere in there. If that is not the case, then launch a file explorer app (example apps are ASTRO File Manager or X-Plore) and browse to the Pictures/camera directory where you should see your images. The next time your media gets re-indexed (phone reboot, or a re-index triggered from elsewhere), you should see these pictures in your gallery/photo apps. If you want to refresh your media programatically, here might help. Finally, make sure you have the READ_EXTERNAL_STORAGE permission in your Android manifest as specified this (Android doc).
2) If you want to save images to be only available to your application, you need to save them to your application's internal data directory. Take a look at this straight from the Android doc. Make sure to use the MODE_PRIVATE flag.
3) For this, you would want to store the file path somewhere accessible to your app. Either you could save your file paths to a text file with some other text data, or you could use a sqlite database. Finally, you could use an ORM like ORMLite for Android to save a java object which might hold data for your picture and have some fields you want to persist (title, description, path, etc). Here and here is an intro on how to get started with SQLite database in Android (straight from the official doc). If you want to use ORMLite, there is plenty of information on their site here. The developer has spent a lot of time answering StackOverflow questions..
All of your questions can be answered with a few simple Google searches. They are very standard and basic things to do in Android, so you should be able to find a plethora of information and tutorials online.
EDIT:
In response to your comment about the second question. This is what I would probably do (or something similar):
Note that I didn't test this. It's from the top of my head. If you have more issues comment here!
Activity code...
mImageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = CameraUtils.getOutputMediaFileUri(currentActivity, CameraUtils.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE)
{
if (resultCode == RESULT_OK)
{
String pathToInternallyStoredImage = CameraUtils.saveToInternalStorage(this, imageUri);
// Load the bitmap from the path and display it somewhere, or whatever
}
else if (resultCode == RESULT_CANCELED)
{
//Cancel code
}
}
}
CameraUtils class code...
public static Uri getOutputMediaFileUri(int type)
{
return Uri.fromFile(getOutputMediaFile(type));
}
public static File getOutputMediaFile(int type)
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "camera");
createMediaStorageDir(mediaStorageDir);
return createFile(type, mediaStorageDir);
}
private static File getOutputInternalMediaFile(Context context, int type)
{
File mediaStorageDir = new File(context.getFilesDir(), "myInternalPicturesDir");
createMediaStorageDir(mediaStorageDir);
return createFile(type, mediaStorageDir);
}
private static void createMediaStorageDir(File mediaStorageDir) // Used to be 'private void ...'
{
if (!mediaStorageDir.exists())
{
mediaStorageDir.mkdirs(); // Used to be 'mediaStorage.mkdirs();'
}
} // Was flipped the other way
private static File createFile(int type, File mediaStorageDir ) // Used to be 'private File ...'
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = null;
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir .getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
}
else if(type == MEDIA_TYPE_VIDEO)
{
mediaFile = new File(mediaStorageDir .getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
}
return mediaFile;
}
public static String saveToInternalStorage(Context context, Uri tempUri)
{
InputStream in = null;
OutputStream out = null;
File sourceExternalImageFile = new File(tempUri.getPath());
File destinationInternalImageFile = new File(getOutputInternalMediaFile(context).getPath());
try
{
destinationInternalImageFile.createNewFile();
in = new FileInputStream(sourceExternalImageFile);
out = new FileOutputStream(destinationInternalImageFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
}
catch (IOException e)
{
e.printStackTrace();
//Handle error
}
finally
{
try {
if (in != null) {
in.close();
}
if (out != null) {
in.close();
}
} catch (IOException e) {
// Eh
}
}
return destinationInternalImageFile.getPath();
}
So now you have the path pointing to your internally stored image, which you can then manipulate/load from your onActivityResult.
I got this code (from android web) that stores make a file location to store the image once started the activity
{
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */ private static
Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */ private static
File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
then i start my activity like this:
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
and then when i get the result on:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... }
i saw that debugging it, "data" is null..
I did the same thing but without adding the
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
and when i add no extra i recieve data info..
guess i have something wrong on writing/reading?? but how? i copyed from the android web!!
I do have permision camera writing reading external storage!
Help!!!!!!!!!!!!!!!
When you specify MediaStore.EXTRA_OUTPUT flag for your intent, the taken picture will be stored in your phone storage and no data will be returned.
from Docs:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT.
When you use the approach to store taken picture, you have to pass URI together with the intent to tell where to store taken picture
NightCrawler Gave a link on how to get data back onActivityResult
Copying the most important portion:
YourActivity extends Activity{
onCreate{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
onActivityResult(parameters..) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
yourImageView.setImageBitmap(photo);
}
}
}
I use the following code to call existed camera :
// New intent to Camera feature
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
Uri fileUri = Uri.fromFile((new File((new Date()).toString()))); // create a file to save the video
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
I can capture photo, but can not record the video, I received the error Warning : Camera failed
I try to do something related to some solutions but can not receive good result. (Although reset the phone)
Please tell me how to fix this,
Thanks,
P/s : Device - Samsung Galaxy Tab 7 2.2.1
EDIT :
I use the following code to receive the response, and response the result resultCode == RESULT_CANCELED
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
Toast.makeText(this, "User cancelled the video capture", Toast.LENGTH_SHORT).show();
} else {
// Video capture failed, advise user
Toast.makeText(this, "Warning : Camera failed", Toast.LENGTH_SHORT).show();
}
I compared your code with Android Guide. The only difference is the file uri. You can try the Google's sample code to get the file uri:
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}