XMLHttpRequest in Cordova for android - android

I'm actually stuck with a problem. Building a app in Cordova, for Android. I need to download a PDF from a variable path in the server. With a documentation from Cordova said "Transition off of cordova-plugin-file-transfer", located here , I tried this:
var oReq = new XMLHttpRequest();
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
oReq.open("GET", endereco, true);
// Define how you want the XHR data to come back
oReq.responseType = "blob";
oReq.onload = function (oEvent) {
var blob = oReq.response; // Note: not oReq.responseText
if (blob) {
console.log("WORKS??");
} else console.error('we didnt get an XHR response!');
};
oReq.send(null);
where "endereco" is a variable where I store the pdf path. So, I'm testing and testing, but maybe someone got some pointers in how to implement this. Right now it just log "WORKS??", so I actually connected successfully. But what now?
1 - so, I made a request, but the file was saved? Couldn't find nothing in my mobile. How can I save said blob in a folder, with the same name and extension from the server?
So, if someone can at least send me to some proper examples or documentation, it would help a lot. Right now I'm reading all on MDN Web Docs, but I'm fairly noob with this type of code :(
thanks in advance!

so, this is how it worked for me! Using the info from the official documentation at cordova, formerly named "cordova-plugin-file" (link), and the amazing info from this page with examples "CORDOVA FILE PLUGIN EXAMPLES" (link) it worked. It could use some cleanup and some error callbacks, but right now I can run this, and download and save an pdf to my android. Hope it helps someone! B-)
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
var fileURL;
var req = new XMLHttpRequest();
req.open("GET", endereco, true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
console.log(blob.type);
console.log("WORKS!");
console.log(fileURL);
// cordova.file.etc is where you will save the file. In this case, inside the app folder, in the main storage in Android
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
// the 'temp.pdf' is the name you want for your file.
directoryEntry.getFile('temp.pdf', { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
// great success!
console.log('Write of file completed.');
};
fileWriter.onerror = function (e) {
// Meh - fail
console.log('Write failed');
};
fileWriter.write(blob);
} );
} );
});
};
req.send();}

Related

Cordova and Tone.js "Error: buffer is either not set or not loaded" when i try to load an mp3 file

maybe you can give me a hand, I've been looking for all information, in order to solve this problem of mine, but nothing, I can't use the player with cordova ...
in practice I can't load mp3 files, whether they are both locally and remotely, I always get this error: "Error: buffer is either not set or not loaded", the files in the path are there.
I tried using Tone's oscilloscope to see if I was having trouble loading Tone, but this works fine.
Could it depend on some authorization, particular that I might be missing ?.
For example using cordova media plugin I can reproduce the audio, but I need to use Tonejs.
Do you have any ideas, what this might depend on. or what could I try to do? ...
even this simple example, after the device ready does not go:
const player = new Tone.Player("https://tonejs.github.io/audio/berklee/gong_1.mp3") .toDestination();
Tone.loaded().Then(() => {
player.start ();
});
You who have already worked with Tone and Cordova, give me hope that it can be used in some way, let me know if you have any ideas thanks in advance!
--- UPDATE:
Currently when the app starts, I behave like this (I state that it is a porting of the code developed for a website and that everything works correctly loading it, etc.):
let myLoader_File = function functionOne(test) {
var androidFixPath = cordova.file.applicationDirectory
console.log("Entered function");
return new Promise((resolve, reject) => {
let CaricatorePlayers = new Tone.Players({
Beep: androidFixPath + "sample/Beep.mp3",
Clave: androidFixPath + "sample/Clave.mp3",
}).toDestination();
resolve(
CaricatorePlayers
//"ok tutti i file sono stati caricati!"
);
reject("si รจ verificato un errore!");
});
};
function onDeviceReady() {
$('#fade-wrapper-flash').fadeOut(1000);
$('#fade-wrapper').fadeIn();
//attach a click listener to a start button
document.querySelector('#fade-wrapper').addEventListener('click', async () => {
await Tone.start();
console.log('audio is ready');
myLoader_File().then((res) => {
console.log(`The function recieved with value ${res}`)
MultiPlayers = res;
console.log(MultiPlayers)
try {
// Play
MultiPlayers.player("Beep").start();
$('#fade-wrapper').fadeOut();
preLoad();
} catch (error) {
console.log(error);
console.log("IN ERRORE RICARICO");
}
}).catch((error) => {
console.log(`Handling error as we received ${error}`);
console.log("IN ERRORE RICARICO");
$('#fade-wrapper').fadeIn();
});
});
}
I posted an answer, here, which also solves this problem.
I don't know if the solution is the only possible way, or the best,
in order to access the folders locally, I made these changes to the call. Using an XMLHttpRequest object
which can be used, to request data from a web server, I got a Blob object, which I then passed to the Tone player.

Cordova - Is it possible to list .bap files inside Android tablet directory "internal storage/bap"?

I'm totally new to Cordova and my current project happens to be implemented with that. I would need a way to read and list files inside a directory located at Internal storage/bap.
I've tried almost every possible way Google has given to me but without luck. If someone has any idea or could point me in the right direction, it would be really appreciated!
Edit
Managed to at least log the files with the following function, just had to be exact with the path and pass a full native path to the desired directory:
function listDir(path: string): any {
window.resolveLocalFileSystemURL(
path,
function(directory) {
var reader = directory.createReader();
reader.readEntries(
function(entries: any) {
console.log("entries inside listDir");
console.log(entries);
},
function(err: any) {
console.log(err);
}
);
},
function(err) {
console.log(err);
}
);
}

How to make ionic application read in json data from .json file that is local to application

I have a Cordova app that uses the ionic framework. I have many json data files that I put in the www/json folder in my app's file tree. I am using angularJS http calls to access them.
When I test my app in chrome (using "ionic serve" in the terminal) it works fine but when I test it on an android device(nexus 5 with Android 6.0 Marshmallow) it no longer works.
Sample code
function getBookNames() {
return $http.get("..\\bookfolder\\Books.json")
.then(function (data) {//if success than do
return data.data;
}, function (reason) {// if fail than do
// maybe tell the user what happened...
});
}
I have tried adding
var path = "";
if (ionic.Platform.isAndroid()) {
path = "\\android_asset\\www\\";
}
function getBookNames() {
return $http.get(path + "..\\bookfolder\\Books.json")
.then(function (data) {//if success than do
return data.data;
}, function (reason) {// if fail than do
// maybe tell the user what happened...
});
}
when I am debugging the app on my phone I get the following error.
GET file:///android_asset/bookfolder/Books.json net::ERR_FILE_NOT_FOUND
If anyone knows what I am doing wrong or of a better way to access local .json files please let me know. Thanks!
Use slash / character, not backslash \. Also, put bookfolder inside /android_asset/www
$http
.get('/android_asset/www/bookfolder/books.json')
.then(function(response){ return response.data });

Phonegap - Local storage not working - Android

I'm using Local Storage to pass values between pages in order to create a scroll to effect (user clicks link and is scrolled to particular part of the page based on ID)
I was previously using cookies but that didn't seem to work on Android, I read that local storage was supported so switched over to that. It works completely fine when in the browser but as soon as its packaged as a native app I lose all functionality? The API states that it should be supported, any ideas?
Here's my code:
Base URL:
var storage = window.localStorage;
$("a.scroll_link").click(function(event) {
event.preventDefault();
var value = $(this).attr("id");
storage.setItem("key",value);
console.log(value);
window.location=$(this).attr("href");
});
Receiving URL:
$(function () {
var value = window.localStorage.getItem("key");
if (value != "" && value != "undefined" && value != null) {
var storage = window.localStorage;
storage.setItem("key",value);
var scroll_type = "";
if ($.browser.webkit) {
scroll_type = "body";
} else {
scroll_type = "html";
}
$(scroll_type)
.stop()
.animate({
//get top-position of target-element and set it as scroll target
scrollTop: ($("#" + value).offset().top - 25)
//scrolldelay: 1.5 seconds
}, {
duration: 1500,
complete: function () {
storage.removeItem("key");
},
});
}
});
The code works fine in the browser just not natively, any ideas?
Thanks,
Use document.addEventListener("deviceready", onDeviceReady, false) instead of $(function(){...}
http://docs.phonegap.com/en/2.5.0/cordova_events_events.md.html#deviceready
1.Glad to know you solve your first problem. As gmh04 say, I think you should replace your init event with 'deviceready' which is triggered when the app start running.
2.
You mean window.localStorage.getItem("key") return null in Receiving URL?
I do not exactly encounter a problem as what you describe. However, you may try to move your code in receiving url to the same page of base url. I have tried for times and be very sure that the localStorage will work in the same page.
I would like add that there's a bug on the 2.6.0 version of cordova.js that make localStorage don't work on Android:
https://issues.apache.org/jira/browse/CB-3063
On the 2.5.0 version it works perfectly, and it is already fix on the 2.7.0 rc.

FIle API - Phonegap?

Can anybody explain how to list a folder of files on a page using the Phonegap File API for Android?
I would like to list all .mp3 files if possible, but have read through all the phonegap docs (http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html) and cant figure it out at all!
it is a bit of a pain in the #$$ but doable. Start with this code:
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("Music", {create: false, exclusive: false}, getDirSuccess, fail);
}
function getDirSuccess(dirEntry) {
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
function readerSuccess(entries) {
var i;
for (i=0; i<entries.length; i++) {
// Assuming everything in the Music directory is an mp3, go nuts
// otherwise check entries[i].name to see if it ends with .mp3
}
}
I'm writing all this example code outside of an IDE so there may be bugs but that should get you going.
Paul, did you add a fail() function? That will be required in Simon's example code. The api docs example has:
function fail(evt) {
console.log(evt.target.error.code);
}
You could also save one step in Simon's code if you just wanted a proof of concept, since fileSystem.root is already a dirEntry (and it saves you the potentially buggy step of having to use a directory name such as "Music" which might or might not be there):
function onFileSystemSuccess(fileSystem) {
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
function readerSuccess(entries) {
var i;.......
which works for me.
However, what I get are the contents of the root directory of the app, apparently, my app being called be.qan.blaActivity, so, if I ask it for fileSystem.root.name it tells me "be.qan" and the fileSystem.root.path is undefined. Thus, my question here would be: how can I break out of this sandbox, if that is indeed what I am sitting in, and can I access the sd_card directories or other parts of the file system (since iOS still does not even have external storage)?
What I am getting by way of file names in readerSuccess are names such as "databases", "app_database", "cache" and "lib" which do not even show up when I do a search with Astro FileManager, so I strongly suppose they are part of a virtual file system that Cordova is creating for the app or so. Probably there is still a lot I am missing and folks more knowledgeable than I can set me straight, but that's what I am guessing so far.
Hi I use this code and it works for me .. can try it
$('#recordingList').on('pagecreate', function(event) {
generateRecordingList();
});
function generateRecordingList(){
//request for the file system
window.resolveLocalFileSystemURI("file:///sdcard/rem", onFileSystemSuccess, onError);
}
function onFileSystemSuccess(fileSystem){
alert("FileSystem success : " + fileSystem.name);
}
function onError(error){
alert(error.target.error.code);
}

Categories

Resources