unable to use internal storage in android - android

I'm learning from treehouse and building a self destructing messaging app tutotrial link now the instructer is saying save files in external storage but since i don't have a device with external storage i want to save file in internal storage and i wrote this code but it seems not working
private Uri getOutputMediaFileUri(int mediaType) {
String appName = null;
File mediaStorage = null;
if(isExternameStorageAvailable()){
// 1. get the external storage directory
appName = MainActivity.this.getString(R.string.app_name);
mediaStorage = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appName);
// 2. create our subdir
if(!mediaStorage.exists()){
if(!mediaStorage.mkdirs()){
Log.e(TAG, "Failed to create directory");
return null;
}
}
// 3. create a file name
// TODO: 05 05
// 4. create the file
}else{
appName = MainActivity.this.getString(R.string.app_name);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
mediaStorage = contextWrapper.getDir(appName, Context.MODE_PRIVATE);
if(!mediaStorage.exists()){
if(!mediaStorage.mkdirs()){
Log.e(TAG, "Failed to create directory");
return null;
}
}
}
File mediaFile = null;
Date now = new Date();
String timeStampe = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);
String path = mediaStorage.getPath() + File.separator;
if(mediaType == MEDIA_TYPE_IMAGE){
mediaFile = new File(path + "IMG_" + timeStampe + ".jpg");
}else if(mediaType == MEDIA_TYPE_VIDOE){
mediaFile = new File(path + "VID_" + timeStampe + ".mp4");
}
Log.d(TAG, "FILE:" + Uri.fromFile(mediaFile));
return Uri.fromFile(mediaFile);
}
all the Uri object is returning null

Maybe you can try this, I used this to access and make directory in internal storage:
String internalPath = Environment.getRootDirectory().getAbsolutePath();

Don't think of external storage as a sd/memory stick. It will exist on your device as a virtual folder on your device.
All Android devices have two file storage areas: "internal" and "external" storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into "internal" and "external" partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.
More at...
http://developer.android.com/training/basics/data-storage/files.html#InternalVsExternalStorage

Related

Save Java.io.File to Android FileSystem on KitKat and above

I'm working on an app that saves thermal images from a FLIR camera to the SD Card on the phone.
I'm using Android Marshmallow and I have to use the FLIR SDK.
In the FLIR SDK is a class "Frame". The class has a method "Frame.save", that needs a Java.io.File to save a thermal image: This is from the documentation:
public void save(java.io.File file,
RenderedImage.Palette previewPalette,
RenderedImage.ImageType previewImageType)
throws java.io.IOException,
java.lang.IllegalArgumentException
Saves a thermal JPEG file, which has a rendered visual preview and embedded thermal data
When I understand it right, on KitKat or higher I have to use the Storage Accsess Framework. So I used it. Send a Intent and get back a Uri to a picked folder on the SD Card. Now to the tricky part. This funktion should create a File and return a Java.io.File that ready for the "Frame.save" method.
public File getJavaFile (String Name, Uri myUri) {
DocumentFile pickedDir = DocumentFile.fromTreeUri(context, myUri); // Document file aus URI
DocumentFile DocumentFile = pickedDir.createFile("image/plain", Name + ".jpg" );
File file = new File(DocumentFile.getUri().getPath());
if(file.canWrite()){
Log.d(TAG + "/getJavaFile", "File can write");
}else {
Log.e(TAG + "/getJavaFile", "File cannot write");
}
Log.d(TAG + "/getJavaFile:", "File Created:" + file.getPath());
return file;
}
The file that the function return is not readable or writeable...
Otherwise, when I try to create a File directly, like so:
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/saved_images");
Log.d(TAG, file.getPath());
Then the the system always gives me this emulated folder:
E/MainActivity: /storage/emulated/0/saved_images
So the question is: How to get a useable Java File, thats stored on the public storage space... Thank you for your time!

store video file on external sdcard in ionic cordova

I have done coding for take video using Media capture plugin and I am also using File Plugin and File transfer plugin. I have done with taking video and store in internal storage in specific folder.
I am doing this in both android and IOS.
Now, what I want, is there any way to check weather device has external sd card inserted or not and then save video on sd card instead of internal storage.
Try this,
private static File getOutputMediaFile(int type){
// Check that the SDCard is mounted
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraVideo");
// Create the storage directory(MyCameraVideo) if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
output.setText("Failed to create directory MyCameraVideo.");
Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
Toast.LENGTH_LONG).show();
Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
return null;
}
}
// Create a media file name
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
Follow this link for your reference, this link will help you to store video file on external sdcard in ionic cordova.
http://androidexample.com/Camera_Video_Capture_And_Save_On_SDCard_-_Android_Example/index.php?view=article_discription&aid=123
I hope you solve your problem very soon.

Android: When I save a file in the phone's internal memory will store Where's that file? How can I access it path?

we have 2 memories for store files:
1- phone memory
2- sd card memory
now :
I can access to files and roots in sdcard memory with Environment.getExternalStorageDirectory ... and return : /storage/sdcard0 this is ok.
but :
When i store files and media (music,pic, ...) in phone memory, how can to get path phone memory?
There are different ways of storing and retrieving application data; SharedPreferences, Internal Storage, External Storage.
- SharedPreferences basically restricts other apps from accessing the data.
- Internal Storage basically stores the data in Phone memory
- External Storage basically stores the data in any other memory cards which can be mounted or unmounted.
If I understand your question properly, then you are interested in External Storage - Public files which basically stores the files in External storage and allows any other apps / user to access the file.
For example:
File sample = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
For app's internal file directory, use
getFilesDir();
For external storage, use
Environment.getExternalStorageDirectory();
Okay, I usually use this helper class to save my media files:
/**
* This class create, name given the timestamp and save a multimedia file in the Environment.DIRECTORY_PICTURES folder
* This location works best if you want the created images to be shared
* between applications and persist after your app has been uninstalled.
*/
public class FileManager {
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
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){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), VideoRecordingActivity.TAG);
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 to use it I will just do:
File currentFile= FileManager.getOutputMediaFile(2);
Note: The media file will be created in sdcard/Pictures/AppName but to be able to see them with your file browser make sure to update your mediaScanner:
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{file.getPath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, final Uri fileUri) {
//Eventually some UI updates
}
});

Not able to write to app specific directory in Android SD card

I learnt that from KitKat an application can only write to its specific directory.
But strangely i am not able to write into my specific application directory also.
Code to get the sd card directory
Process process = new ProcessBuilder().command("mount").start();
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
// Output the line of output from the mount command
logger.debug(" {}", line);
if (line.startsWith("/dev/block/vold/")) {
String[] tokens = line.split(" ");
if (tokens.length >= 3 && (tokens[2].equals("vfat") || tokens[2].equals("exfat"))) {
String path = tokens[1];
File file = new File(path);
if (file.exists() && file.isDirectory()) {
logger.debug("Detected SD card at {}", file.getPath());
if (!file.canWrite()) {
logger.warn("The SD card path {} is reporting that it is not writable", file.getPath());
}
// path = basecontext.getExternalFilesDir(null).getPath();
return path;
}
}
}
}
Code to get a file
Here is how i construct the file path :
sdCardDirectory is the directory which i get like this: /storage/extSdCard/
directory and sub directory are my application sepcifc subdirectoryies but are obviously inside the app specific directory in the application
sdCardDirectory + File.separator + "Android" + File.separator + "data" + File.separator
+ <my app package> + File.separator + subdirectory
+ File.separator + directory+ File.separator + document.getRepositoryId() + FILENAME_SEPARATOR
+ fetchObjectId(document);
Where the ids retrieved are simple alpha numeric strings for e.g. aBc45ef_0
randomAccessFile = new RandomAccessFile(file, "rw");
I am getting
java.io.FileNotFoundException: /storage/extSdCard/Android/data/myapp/cache/downloaded/OhCQL_RQl8IJcVlO5T1MX4-3SQg_mMDT5PWtf-IYmE0: open failed: EROFS (Read-only file system)
Where myapp is the my application package name.
UPDATE This is the link to Android bug which i have opened https://code.google.com/p/android/issues/detail?id=69549&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars
cheers,
Saurav
But strangely i am not able to write into my specific application directory also.
That code is not necessarily going to give you anything that you can use. Please use getExternalFilesDirs() (note the plural); the second and subsequent entries in the returned list will be from removable storage, where available.
You may wish to read my blog post on Android 4.4 and removable storage for more background.

How to save files on different mobile devices with and without sd cards?

I uploaded my app to google play and after this I found that my application has not been working in all devices that i checked except my own...
I believe that the problem is a result of the file save location, I use the following code:
But what happens in devices without SD Card?
in the logcat i recieve error "failed to create directory"
// Step 4: Set output file
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO)
.toString());
outputFileName = getOutputMediaFile(MEDIA_TYPE_VIDEO).toString();
/** 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_MOVIES),
"Your_voice");
// 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("Your_voice_App", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyy_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "Your_voice" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
You can then review, edit and quickly share them without needing to boot up your PC. It'll also allow you to watch videos stored on the card, meaning you don't need to clog up your precious internal storage with huge video files.
http://resultplanet.org/

Categories

Resources