Cordova 7.x creating dir error - javascript

When building my app I've encountered the couldn't find Android SDK error. Updating Cordova from 4.x to 7.x did the trick of fixing this issue. However, now my app doesn't write directories anymore (in this case 1 directory in the root folder). The fileSystem.root.getDirectory() returns error code 12 (PATH_EXISTS_ERR). Since it's an directory in the root, it should work right?
Anybody an idea how this issue can be solved?
My code:
function writeFile(file, data, functionName) {
console.log('writeFile');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log('requestFileSystem');
console.log(config.folder);
fileSystem.root.getDirectory(config.folder, {create: true}, function(dirEntry){
console.log('getDirectory');
dirEntry.getFile(file, {create: true, exclusive: false}, function(fileEntry){
console.log('getFile');
fileEntry.createWriter(function(fileWriter){
console.log('writing...');
fileWriter.write(data);
if(functionName != '') {
console.log('writed');
window[functionName](true);
}
console.log('end writing');
}, function(writeError){
console.log(writeError);
});
}, function(fileError){
console.log(fileError);
});
}, function(dirError){
console.log(dirError)
});
}, function(fileSystemError){
console.log(fileSystemError)
});
console.log('end writeFile');
}

Totally forgot about the runtime permissions since Android 6.0. Added a runtime permission plugin to make it work again.

Related

Unable to create directory in android using cordova-plugin-file

I am trying to create a directory in phone storage using this code and this plugin cordova-plugin-file.
function createDirectory(fileSystem){
var directoryEntry = fileSystem.root;
var folderName = cordova.file.externalRootDirectory + 'SomeFolder/';
console.log(folderName);
directoryEntry.getDirectory(folderName, { create: true, exclusive: false }, function(parent){
console.log(parent);
}, function(err){
console.log('Error while creating directory.',err)
})
}
But it throws this err :
`Error while creating directory. FileError {code: 5}`
How to solve this error and create a directory in root of phone storage ?
The documentation only shows that this error code : 5 means ENCODING_ERR

FileOpener2 causing Attempt to invoke virtual method in cordova.js file on Android 6.0 or higher

We use FileOpener2 plugin for cordova to open a downloaded .apk file from our servers. Recently, we found that Android 6.0 or higher devices are throwing an exception only on the file open process. We were able to trace this down to the cordova.js file, where the posted exception occurs. We have yet to find a cause or a fix, but have put a workaround in place. Any info would be amazing on this so we can maintain our in-app self updating process going on all Android devices.
Code (Working on Android <= 6.0):
// we need to access LocalFileSystem
window.requestFileSystem(LocalFileSystem.PERSISTENT, 5 * 1024 * 1024, function (fs) {
//Show user that download is occurring
$("#toast").dxToast({
message: "Downloading please wait..",
type: "warning",
visible: true,
displayTime: 20000
});
// we will save file in .. Download/OURAPPNAME.apk
var filePath = cordova.file.externalRootDirectory + '/Download/' + "OURAPPNAME.apk";
var fileTransfer = new FileTransfer();
var uri = encodeURI(appDownloadURL);
fileTransfer.download(uri, filePath, function (entry) {
//Show user that download is occurring/show user install is about to happen
$("#toast").dxToast({
message: "Download complete! Launching...",
type: "success",
visible: true,
displayTime: 2000
});
////Use pwlin's fileOpener2 plugin to let the system open the .apk
cordova.plugins.fileOpener2.open(
entry.toURL(),
'application/vnd.android.package-archive',
{
error: function (e) {
window.open(appDownloadURL, "_system");
},
success: function () { console.log('file opened successfully'); }
}
);
},
function (error) {
//Show user that download had an error
$("#toast").dxToast({
message: error.message,
type: "error",
displayTime: 5000
});
},
false);
})
Debugging Information:
THIS IS NOT OUR CODE, BUT APACHE/CORDOVA CODE
Problem File: cordova.js
function androidExec(success, fail, service, action, args) {
// argsJson - "["file:///storage/emulated/0/download/OURAPPNAME.apk","application/vnd.android.package-archive"]"
//callbackId - FileOpener21362683899
//action - open
//service FileOpener2
//bridgesecret - 1334209170
// msgs = "230 F09 FileOpener21362683899 sAttempt to invoke virtual method 'android.content.res.XmlResourceParser //android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference"
var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);
// If argsJson was received by Java as null, try again with the PROMPT bridge mode.
// This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.
if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "#Null arguments.") {
androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);
androidExec(success, fail, service, action, args);
androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);
} else if (msgs) {
messagesFromNative.push(msgs);
// Always process async to avoid exceptions messing up stack.
nextTick(processMessages);
}

Unhandled Promise rejection: push.on is not a function

I am using Ionic 2.
I get this Typescrpt error when trying to set up Push Notifications. I have copied this sample code from a tutorial, so would have expected it to work. I must have something wrong. Any ideas please:
Unhandled Promise rejection: push.on is not a function ; Zone: angular ; Task: Promise.then ; Value:
TypeError: push.on is not a function
push.on('registration', function (data) {
typescript
import { Push } from 'ionic-native';
.
.
pushNotifications(): void {
var push = Push.init({
android: {
vibrate: true,
sound: true,
senderID: "xxxxxxxxxxxxxxxxxxx"
},
ios: {
alert: "true",
badge: true,
sound: 'false'
},
windows: {}
});
push.on('registration', (data) => {
console.log(data.registrationId);
alert(data.registrationId.toString());
});
push.on('notification', (data) => {
console.log(data);
alert("Hi, Am a push notification");
});
push.on('error', (e) => {
console.log(e.message);
});
}
Make sure to check if 'window.cordova' is available before using the plugin. Are you actually testing on a device or in browser? Cordova is not available within browser.
EDIT
To make sure your code editor knowns what 'window.cordova' is, make sure you installed cordova typings.
npm install typings -g
typings install dt~cordova --save --global

ionic.bundle.js:25642 Error: [$injector:unpr] Unknown provider: $cordovaGeolocationProvider <- $cordovaGeolocation <- AgeCtrl

I am currently in the starting phase of building an app via Ionic. Right now i want to implement the cordova geolocation in it. However this keeps giving an error when opening it. For testing purposes i use ionic serve and check it in localhost.
angular.module('starter', ['ionic','ionic.service.core', 'ui.router'])
.controller('AgeCtrl', function ($scope, $state, $http, $cordovaGeolocation) {
$scope.toggleItem = function (item) {
item.checked = !item.checked;
};
$scope.items = [
{ id: '0-12' },
{ id: '12-18' },
{ id: '18-30' },
{ id: '30-65' },
{ id: '65+' }
];
$scope.time = Date.now();
$scope.weather = $http.get("http://api.openweathermap.org/data/2.5/weather?q=Amsterdam&units=metric&APPID=...").then(function(resp) {
console.log("success", resp);
}, function(err) {
console.log("error");
})
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
$scope.Confirm = function (){
$state.go('home');
}
})
Is there any place i have made a mistake which causes this problem?
Ionic serve only emulates the application in the browser.
You do not get access to the Cordova plugins within the browser.
To get the libraries included you need to run the app on the device after adding a specific platform depending on what device you have.
For iOS:
Ionic platform add ios
For android:
ionic platform add android
After the platforms are added you can build and run on device using the following command
For iOS:
ionic run iOS
For android:
ionic run android
I believe the issue is with your ngCordova installation .
do below steps -
1- install --------------> bower install ngCordova
2- include in index.html above cordova.js ------------------> script src="lib/ngCordova/dist/ng-cordova.js"
3- inject -------------> angular.module(starter, ['ngCordova'])
run IONIC serve and issue will be gone .. If it still shows error that /dist/ngCordova is not present then go to location manually where ng cordova is installed and copy it to the path e.g. - /lib/ngCordova/dist/...
it will definitely resolve your issue
I think it's not referenced as $cordovaGeolocation in ionic. Try navigator.geolocation.getCurrentPosition instead?

phonegap deleting a file within a sub folder

I want to deleate a file in phonegap android application.
file is exists in subfolder.
I am finding a sample code on the internet.But I can't see.
Phonegap docs
is not enough for me.Can someone answer me how to delete a file within a subfolder.
function deleteFilelists(tx,results)
{
var fileName = "cdvfile://localhost/persistent//flower.jpg"
removefile(fileName);
function removefile(fileName){
fileSystem.root.getFile(fileName, {create: false, exclusive: false}, gotRemoveFileEntry, fail);
}
function gotRemoveFileEntry(fileEntry){
fileEntry.remove(success, fail);
}
function success(entry) {
alert("Removal succeeded");
}
function fail(error) {
alert("Error removing file: " + error.code);
}
}

Categories

Resources