How to Get Documents in an Android Directory That Phonegap Will See

How to get documents in an android directory that PhoneGap will see

Well now. Part of my problem was that I got bit by the asynchronous nature of the filesystem / cordova-plugin-file API on cordova. I had to do some code refactoring to get the file list to show up properly, but once I did, the files displayed properly regardless of where they were on the device.

Here's the applicable code. Note that you'll need the cordova-plugin-file added to your Cordova/PhoneGap project, and that it won't work in the browser. I actually have this block inside another if/then block -- if it's running in a browser, show the html5 <input type=file>, if it's in a mobile device, show this block:

var localURLs    = [
cordova.file.dataDirectory,
cordova.file.documentsDirectory,
cordova.file.externalApplicationStorageDirectory,
cordova.file.externalCacheDirectory,
cordova.file.externalRootDirectory,
cordova.file.externalDataDirectory,
cordova.file.sharedDirectory,
cordova.file.syncedDataDirectory
];
var index = 0;
var i;
var statusStr = "";
var addFileEntry = function (entry) {
var dirReader = entry.createReader();
dirReader.readEntries(
function (entries) {
var fileStr = "";
var i;
for (i = 0; i < entries.length; i++) {
if (entries[i].isDirectory === true) {
// Recursive -- call back into this subdirectory
addFileEntry(entries[i]);
} else {
fileStr += (entries[i].fullPath + "<br>"); // << replace with something useful
index++;
}
}
// add this directory's contents to the status
statusStr += fileStr;
// display the file list in #results
if (statusStr.length > 0) {
$("#results").html(statusStr);
}
},
function (error) {
console.log("readEntries error: " + error.code);
statusStr += "<p>readEntries error: " + error.code + "</p>";
}
);
};
var addError = function (error) {
console.log("getDirectory error: " + error.code);
statusStr += "<p>getDirectory error: " + error.code + ", " + error.message + "</p>";
};
for (i = 0; i < localURLs.length; i++) {
if (localURLs[i] === null || localURLs[i].length === 0) {
continue; // skip blank / non-existent paths for this platform
}
window.resolveLocalFileSystemURL(localURLs[i], addFileEntry, addError);
}

EDIT (Feb 2018): even if you can see the files on Android File Transfer, you might not get any results back programmatically, even if you have build time permissions set in your Cordova app. This is due to runtime permission checks added to Android (I believe > 6.0). There are a couple plugins that can help get around this; at some point, I'm guessing the file plugin will add automatic requests for it as well. Here's what I've done as of Cordova cli-7.0.1:

In your config.xml, set the needed app permissions. You'll need READ_EXTERNAL_STORAGE (and write as well, if you are going to do that). I'm also adding two plugins that are referenced below:

<plugin name="cordova-plugin-device" source="npm" spec="1.1.6" />
<plugin name="cordova.plugins.diagnostic" spec="^3.7.1" />

<config-file platform="android" parent="/manifest" mode="replace">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</config-file>

Then, preferably somewhere in your app's startup code (i.e., the handler for the device ready event), check for the runtime permissions and add them if needed:

if (device.platform === "Android") {
// request read access to the external storage if we don't have it
cordova.plugins.diagnostic.getExternalStorageAuthorizationStatus(function (status) {
if (status === cordova.plugins.diagnostic.permissionStatus.GRANTED) {
console.log("External storage use is authorized");
} else {
cordova.plugins.diagnostic.requestExternalStorageAuthorization(function (result) {
console.log("Authorization request for external storage use was " + (result === cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
}, function (error) {
console.error(error);
});
}
}, function (error) {
console.error("The following error occurred: " + error);
});
}

EDIT (August 2021): Android 10.x and above introduces the concept of scoped storage, which is further refined in Android 11 (see https://developer.android.com/about/versions/11/privacy/storage). Most of this is to tighten up security on your device. What it means for your app is that reading/writing to permanent files should be limited to the two following sandboxed directories if you're a good Android citizen:

  • cordova.file.externalDataDirectory (if you've got an SD card)
  • cordova.file.datadirectory

Unless you have a good reason to be looking around the entire filesystem (and can convince the Google Play store team of this), your app is likely to get rejected if you try to invoke All files access. From the linked article:

Note: If you publish your app to Google Play, carefully read the notice. If you target Android 11 and declare All files access, it can affect your ability to publish and update your app on Google Play.

Getting application directory in phone gap

function gotFS(fileSystem) {
console.log("got filesystem");
// save the file system for later access
console.log(fileSystem.root.fullPath);
window.rootFS = fileSystem.root;
}

document.addEventListener('deviceready', function() {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}, false);

With this code you'll have a DirectoryEntry object for the root directory of your app stored in the global variable "rootFS". You can get the path of that folder like this:

rootFS.fullPath

Get internal application directory in Cordova + android

from cordova file 3.0.0, the default LocalFileSystem.PERSISTENT is the /data/data/app.package

on previous versions you can get it using

window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory, success, fail);

How to check a file's existence in phone directory with phonegap

You could check if the file exists using the FileReader object from phonegap.
You could check the following:

var reader = new FileReader();
var fileSource = <here is your file path>

reader.onloadend = function(evt) {

if(evt.target.result == null) {
// If you receive a null value the file doesn't exists
} else {
// Otherwise the file exists
}
};

// We are going to check if the file exists
reader.readAsDataURL(fileSource);

How to add file in My Documents folder like Whatsapp?

To get Documents directory you should use Environment.DIRECTORY_DOCUMENTS.

To access it:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)


Standard directory in which to place documents that have been created
by the user.

Other directory:

public static String DIRECTORY_ALARMS Standard directory in which to
place any audio files that should be in the list of alarms that the
user can select (not as regular music).

public static
String DIRECTORY_DCIM The traditional location for pictures and videos
when mounting the device as a camera.

public static
String DIRECTORY_DOCUMENTS Standard directory in which to place
documents that have been created by the user.

public static
String DIRECTORY_DOWNLOADS Standard directory in which to place files
that have been downloaded by the user.

public static
String DIRECTORY_MOVIES Standard directory in which to place movies
that are available to the user.

public static
String DIRECTORY_MUSIC Standard directory in which to place any audio
files that should be in the regular list of music for the user. public
static String DIRECTORY_NOTIFICATIONS Standard directory in which to
place any audio files that should be in the list of notifications that
the user can select (not as regular music).

public static
String DIRECTORY_PICTURES Standard directory in which to place
pictures that are available to the user.

public static
String DIRECTORY_PODCASTS Standard directory in which to place any
audio files that should be in the list of podcasts that the user can
select (not as regular music).

public static
String DIRECTORY_RINGTONES Standard directory in which to place any
audio files that should be in the list of ringtones that the user can
select (not as regular music).

Can't get access to the root directory phonegap

Hmm... you might want to try window.resolveLocalFilesystemURL() instead of window.requestFilesystem() if you're looking to read the filesystem.

I've got a sample routine that iterates through a bunch of directories here: How to get documents in an android directory that PhoneGap will see. It might help narrow your search.

cordova/phonegap does not make android directory

It does seem like you are using PhoneGap 3.0 and for this version, eclipse is not required (only if you want to use it for coding - compared to PhoneGap 1.0-2.x where eclipse was used to compiled the app, for the latest version it is no longer a requirement).

  1. To begin, you should use the phonegap command instead of the cordova command: phonegap create hello com.example.hello "HelloWorld"

  2. Then navigate to /HelloWorld/ folder

  3. You should see atleast these two key folders /www and /platforms. Inside /www is where you place your HTML files and codes, and /platforms/android gets generated when you compile the app with the following command: phonegap build android.

Note: Avoid making any direct changes to files inside /platforms except for config and manifest files. The other files are dynamically generated when you run the build command. All coding should take place within /www.

One more thing, use the 3.0.0 Getting Started guide.

---- February 2014 Update ----

With the release of Cordova 3.3.0, it seems the PhoneGap team is trying to address the naming confusion. The documentations have been updated to recommend people using the cordova command instead. Do not use the phonegap command anymore.

Here is a fresh installation guide for a guaranteed trouble free set up:

  1. Install Cordova (forget the name PhoneGap from now on).
    For PC:

    C:> npm install -g cordova

  2. From command prompt, navigate to the folder you want to create your project using:

    cordova create hello com.example.hello HelloWorld
    cd HelloWorld

  3. Define the OS you want to suppport, we'll go with Android for this example:

    cordova platform add android

  4. Install plugins (If needed). For example we want the following:


    cordova plugin add org.apache.cordova.device
    cordova plugin add org.apache.cordova.camera
    cordova plugin add org.apache.cordova.media-capture
    cordova plugin add org.apache.cordova.media

  5. Finally, generate the app using:
    cordova build android
    or to directly install the app to your connected device:
    cordova run android

Here is a link to the PhoneGapCordova 3.3.0 Documentation
http://docs.phonegap.com/en/3.3.0/guide_cli_index.md.html#The%20Command-Line%20Interface

Phonegap 3.5.0 Cordova Access to application folder after build app

The application folder itself is read-only (as the File plugin says on it's documentation) as it is the installed package. You can access it with the cordova.file.applicationStorageDirectory on Android and cordova.file.applicationDirectory on iOS with appending the correct path such as www/images/ after it.

You want to store your downloaded files to somewhere like cordova.file.externalDataDirectory on Android and cordova.file.documentsDirectory on iOS and then use those files within your application.



Related Topics



Leave a reply



Submit