I have this app where I take picture or select it from gallery then move it into file-system , save the imgpath for the image into sqlite db and display it, everything works great so far , now when I delete the imgpath from the sqlite db , I want to delete it from file-system at the same time .
$scope.deleteImg = function(imgPath) {
if (!imgPath) {
console.error("No fileName specified. File could not be deleted.");
return false;
} else {
$cordovaFile.checkFile(cordova.file.externalRootDirectory, imgPath.id).then(function() {
$cordovaFile.removeFile(cordova.file.externalRootDirectory, imgPath.id).then(function(result) {
console.log("image '" + imgPath + "' deleted", JSON.stringify(result));
}, function(err) {
console.error("Failed to delete file '" + imgPath.id + "'", JSON.stringify(err));
});
}, function(err) {
console.log("image '" + imgPath.id + "' does not exist", JSON.stringify(err));
});
}
$scope.add = function(path) {
console.log("I AM ADDING TO DB WITH PATH: " + path);
$cordovaSQLite.execute(db, "INSERT INTO imageTable (image) VALUES(?)", [path]).then(
function(res) {
console.log("I AM DONE ADDING TO DB");
}
);
},
function(e) {
alert(e);
};
$scope.ShowAllData = function() {
console.log("I AM READING FROM DB");
$scope.images = [];
$cordovaSQLite.execute(db,"SELECT * FROM imageTable ORDER BY id DESC" ).then( function(res) {
console.log("I FINISHED READING FROM DB");
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
$scope.images.push({
id: res.rows.item(i).id,
image: res.rows.item(i).image
});
}
}
return $scope.images;
}, function(error) {
alert(error);
} );
}
$scope.getImgIDbyName = function(name) {
console.log('[getImgIDbyName] - get image with name: ' + name);
var sql = "SELECT * FROM imageTable WHERE image = '" + name + "';";
console.log(sql);
$cordovaSQLite.execute(db,
sql
).then(
function(res) {
if (res.rows.length > 0) {
if (res.rows.length > 1) {
console.log('[getImgIDbyName] - OOPS more than 1 image returned!!!! ' + name);
} else {
$scope.delete(res.rows.item(0).id);
$scope.deleteImg(imagePath.id);
}
} else {
console.log('[getImgIDbyName] - no image found with name: ' + name);
}
},
function(error) {
alert("error occured: " + error.message);
}
);
}
First download the plugin - cordova plugin add cordova-plugin-file
and then execute the following code
var path = cordova.file.applicationDirectory + '/www/res/image'; // get the absolute path
var filename = "image.png";
window.resolveLocalFileSystemURL(path, function(dir) {
dir.getFile(filename, {create:false}, function(fileEntry) {
fileEntry.remove(function(){
// The file has been removed succesfully
},function(error){
// Error deleting the file
},function(){
// The file doesn't exist
});
});
});
Here is the complete documentation : https://github.com/apache/cordova-plugin-file/#where-to-store-files
Related
I am trying to insert the sensor data into a SQL Server database. I have tried all the possible way to insert the incoming data into database, but I failed. I am new to Nodejs and I really have no idea why these errors are occurred during executing process. It would be great if anyone could help me.
Thank you in advance.
The error I get is:
TypeError: Cannot read property 'writeHead' of undefined.
function addData (req, resp, reqBody, data)
{
try {
if (!reqBody) throw new Error("Input not valid");
data = JSON.parse(reqBody);
//reqBody = JSON.parse(data);
if (data) {//add more validations if necessary
var sql = "INSERT INTO arduinoData (Machine, StartTime, EndTime, LengthTime) VALUES ";
sql += util.format("(%s, '%s', %s, %s) ", data.Machine, data.StartTime, data.EndTime, data.LengthTime);
db.executeSql(sql, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.send200(req, resp);
}
});
}
else {
throw new Error("Input not valid");
}
}
catch (ex) {
httpMsgs.show500(req, resp, ex);
}
};
function sendBackupData()
{
var jsonTable = { "table": [] };
fs.readFile("backup.json", "utf8", function (err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
if (jsonTable.table.length == 0) {
return;
}
for (var index = 0; index < jsonTable.table.length; index++) {
var options = {
url: serverURL,
method: "POST",
form: jsonTable.table.shift()
};
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent backup message!");
} else {
console.log('Error: ' + error);
console.log("CANT'T SEND BACK");
console.log(options.form);
jsonTable.table.push(options.form);
}
});
}
var outputJSON = JSON.stringify(jsonTable);
console.log(outputJSON);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
console.log("Sent backup data!");
});
});
}
function getTime()
{
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
// Unix Time
var unixTime = Math.floor(date / 1000);
// Check if it is day or night
var isDay;
if (date.getHours() >= 8 & date.getHours() < 16)
{
isDay = true;
}
else
{
isDay = false;
}
return [year + '-' + month + '-' + day, hour + ':' + minute + ':' + second, unixTime, isDay];
}
/*
--- Main Code ---
*/
function vibrationStart()
{
/*
Should get:
- Start time and date the vibration started
- Whether it was day or night
Will send the message, if there is network connection, once complete.
Will store message into a JSON file if there is no network connection.
*/
var jsonTable = { "table": [] };
var startTime = getTime();
console.log(startTime[0] + " " + startTime[1]);
var startData = {
machine: machineName,
start_time: startTime[0] + " " + startTime[1],
day_night: startTime[3],
active: "true"
};
const options = {
url: serverURL,
method: "POST",
form: startData
};
var reqBody = [{
Machine : "",
StartTime : ""
}];
reqBody.push({"Machine" : startData.machine,"StartTime" : startData.start_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent starting message!");
sendBackupData();
addData();
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(startData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
return startTime[2];
}
function vibrationStop(startTimeUnix)
{
var jsonTable = { "table": [] };
var endTime = getTime();
console.log(endTime[0] + " " + endTime[1]);
var endTimeUnix = endTime[2];
var lengthTime = endTimeUnix - startTimeUnix;
console.log("Length time: " + lengthTime);
var endData = {
machine: machineName,
end_time: endTime[0] + " " + endTime[1],
length_time: lengthTime,
active: "false"
};
const options = {
url: serverURL,
method: "POST",
form: endData
};
var reqBody = [{
EndTime : "",
LengthTime :"",
}];
reqBody.push({"EndTime" : endData.end_time,"LengthTime" : endData.length_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent end message!");
sendBackupData();
addData()
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(endData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
}
http.createServer(function (req, resp) {
app.get('/', addData);
}).listen(settings.webPort, function () {
console.log("Started listening at: " + settings.webPort);
});
I create test.txt with this code:
=====================
function e(arg){
if (typeof arg === "function") {
return arg;
} else {
return function (er) { console.log('[' + arg + '] ' + er); };
}
}
function rs(dir) {
var fh = dir.createFile(" test.text");
{
fh.openStream('rw', function(fs){
fs.write("Hello ");
fs.close();
}, e('openStream'), 'UTF-8');
}
}
tizen.filesystem.resolve('downloads', rs, e('resolve'), 'rw');
=====================
And try to append some text by this code :
=====================
function append(dir) {
var fh = dir.resolve(" test.text");
{
fh.openStream('a', function(fs){
fs.write(" Tizen .. ");
fs.close();
}, e('openStream'), 'UTF-8');
}
}
tizen.filesystem.resolve('downloads', append, e('resolve'), 'a');
====================
but file contain only last text ('Tizen ..').
how to solve this problem?
thanks
Try the code below. It worked in my case.
var newDir, newFile;
tizen.filesystem.resolve("documents", function(dir) {
newDir = dir.createDirectory("newDir");
newFile = newDir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write("Hello");
fs.close();
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
});
var text2;
tizen.filesystem.resolve("documents", function(dir) {
file = dir.resolve("newDir/newFilePath.txt");
file.openStream(
"a",
function(fs) {
fs.write('Tizen .. ');
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
file.openStream(
"r",
function(fs) {
text2 = fs.read(file.fileSize);
fs.close();
console.log(text2);
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
});
Note: Please check in your project's config.xml file whether you've added the following privileges or not.
<tizen:privilege name="http://tizen.org/privilege/filesystem.read"/>
<tizen:privilege name="http://tizen.org/privilege/filesystem.write"/>
There is a mobile app in which i want to delete the cached images downloaded by a particular user after log out.Suppose user1 logged in and download few images and user2 logged in and downloaded few images.User2 should not see downloaded images of any other user.
downloadFile : function(downloadLink, downloadFileName, downloadFileMimeType) {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
var accessToken = $window.localStorage.getItem(SYSTEM.AUTH_TOKEN);
var options = {
headers : {
'Authorization' : 'Bearer ' + accessToken
}
};
var ext;
if (downloadFileMimeType == 'application/pdf') {
ext = '.pdf';
} else {
ext = '.jpg';
}
var localPath;
if(ionic.Platform.isAndroid()){
localPath = cordova.file.externalCacheDirectory;
}else{
localPath = cordova.file.cacheDirectory;
}
localPath = localPath + downloadFileName.trim().replace(/\s+/g, '-') + ext;
var ft = new FileTransfer();
ft.download(downloadLink, localPath, function(entry) {
$ionicLoading.hide();
console.log("Downloading report on path - " + entry.toURL());
cordova.plugins.fileOpener2.open(entry.toURL(), downloadFileMimeType, {
error : function(e) {
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success : function(fileEntry) {
console.log('File opened successfully');
}
});
}, function fail(error) {
$ionicLoading.hide();
console.log("Error while downloading report with error code - " + error.code);
}, true, options);
}
You can store files downloaded by specific user under a user specific folder in device and delete the same when the other user logs in. Else you can follow some file naming convention specific to the users while storing the files in folder and delete those files specific to particular user when the other user logs in. The sample snippet for directory deletion and its contents using cordova file plugin is as follows:
function clearDirectory() {
if (ionic.Platform.isAndroid()) {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemDirSuccess, fail);
} else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemDirSuccess, fail);
}
function onFileSystemDirSuccess(fileSystem) {
var entry = "";
if (ionic.Platform.isAndroid()) {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("DIRECTORY_TO_DELETE", {
create: true,
exclusive: false
},
function(entry) {
entry.removeRecursively(function() {
console.log("Remove Recursively Succeeded");
}, fail);
}, getDirFail);
}
function getDirFail(error) {
navigator.notification.alert("Error");
};
function fail(error) {
navigator.notification.alert("Error");
};
}
I am building an mobile application using Ionic and Sqlite.I am successful in storing data to the Sqlite database, retrieving the data back from the database and printing it to the console. Now, I am unable to figure out how to populate the data form the database in an ionic list
$scope.load = function() {
$cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
.then(
function(res) {
if (res.rows.length > 0) {
for (var i=0; i<res.rows.length; i++) {
console.log("Product ID: " + res.rows.item(i).productID + " Product Name : " + res.rows.item(i).productName);
}
}
},
function(error) {
console.log("Error on loading: " + error.message);
}
);
}
I need to display res.rows.item(i).productID & res.rows.item(i).productName in an ionic list.
Well, to answer my own question...it turns out to be actually very simple.It just works as normally as other Angularjs arrays. Made the following changes to my code:
$scope.load = function() {
$scope.listItems= [];
$cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
.then(
function(res) {
if (res.rows.length > 0) {
for (var i=0; i<res.rows.length; i++) {
console.log("Product ID: " + res.rows.item(i).productID + " Product Name : " + res.rows.item(i).productName);
$scope.listItems.push(res.rows.item(i));
}
}
},
function(error) {
console.log("Error on loading: " + error.message);
}
);
}
Now you can use ng-repeat or any other ionic element any display the data from sqlite as {{listItems}}.
I have following function which worked fine until i tried to call another assync request from this assync function. If i tried it secondary assync function always returns exception.
"Has bo method 'then'"
Has anybody idea what can causing it and how can i solve it plese?
Thanks for any help.
First assync function
$scope.getData = function() {
var deferred = $q.defer();
var DATE_FROM = dateFrom;
var DATE_TO = dateTo;
// INSTANTIATE DB CONNECTION
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
var numberOfProcessed = 0;
for(var ic=0; ic < dateRanges.length; ic++) {
var sqlQuery =
"SELECT '"+dateRanges[ic].DATE_FROM+"' as DATE_FROM, "+
" '"+dateRanges[ic].DATE_TO+"' as DATE_TO, "+
" COUNT(*) AS DIALS_CNT, "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_APPT+"' THEN 1 ELSE 0 END) AS '"+APPT_CNT+"', "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CONV_NO_APPT+"' THEN 1 ELSE 0 END) AS '"+CONVERS_CNT+"' , "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CANNOT_REACH+"' THEN 1 ELSE 0 END) AS '"+CANNOT_REACH_CNT+"' "+
" FROM "+DIALED_CALLS_TABLE+" dc "+
" WHERE dc.date BETWEEN '"+dateRanges[ic].DATE_FROM+"' AND '"+dateRanges[ic].DATE_TO+"';";
// PRINT QUERY
console.log(sqlQuery);
// PUSH QUERY TO ARRAY
sqlQueries.push(sqlQuery);
// PROCESS TRANSACTION
db.transaction(function(tx) {
// init empty array for results
tx.executeSql(sqlQueries[numberOfProcessed], [], function(tx,results){
for (var i=0; i < results.rows.length; i++){
//process your result from sql
numberOfProcessed++;
row = results.rows.item(i);
// Replace null values
if(row.APPT_CNT == null)
row.APPT_CNT = 0;
if(row.CONVERS_CNT == null)
row.CONVERS_CNT = 0;
if(row.CANNOT_REACH_CNT == null)
row.CANNOT_REACH_CNT = 0;
// End of replacing null values
row.YOUR_GOAL = $rootScope.goalValue;
row.YOUR_DEFICIT = DialsComputeService.computeDailyDeficit(row);
row.SUCCESS_RATE = DialsComputeService.computeSuccessRateDaily(row);
//row.SUCCESS_RATE_SINCE = DialsComputeService.computeSuccessRateSinceStart(row);
// GET DATA IN ASSYNC TASK
DialsComputeService.computeSuccessRateSinceStart.then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
try{
row.SUCCESS_RATE_SINCE = result;
} catch (e) {
$ionicLoading.show({
template: $translate.instant('ERROR'),
duration:1000
});
}
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
// END GET DATA IN ASSYNC TASK
statsData.push(row);
console.log("Result row is: " + JSON.stringify(row));
if(numberOfProcessed == dateRanges.length){
deferred.resolve(statsData); // resolve your promise when you are sure you handled everything
}
}
});
},function (e) {
alert("ERROR: " + e.message);
deferred.reject(e);
});
}
return deferred.promise;
};
Second assync function in service:
computeSuccessRateSinceStart: function(row) {
var deferred = $q.defer();
console.log("Trying to compute daily success rate since until" +row.DATE_TO);
var sqlQuery =
"SELECT " +
"("+
"SELECT COUNT(*) "+
"FROM dialed_calls AS dc "+
"WHERE dc.date < '"+row.DATE_TO+"'" +
") " +
"AS DIALS_CNT ," +
"("+
"SELECT COUNT(dc.call_result) "+
"FROM dialed_calls AS dc "+
"WHERE dc.call_result = 'APPT_CNT' "+
"AND "+
"dc.date < '"+row.DATE_TO+"'" +
") " +
"AS APPT_CNT ;";
console.log(sqlQuery);
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
// GET APPT COUNT
db.transaction(function(tx) {
tx.executeSql(sqlQuery, [], function(tx,results){
// init empty array for results
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
//Udpate date for writeout
//row.DATE = moment(row.DATE).format('ddd DD.M');
console.log("row APPT count is " + JSON.stringify(row));
alert(JSON.stringify(row));
var successRateFromSince;
successRateFromSince = row.APPT_CNT / row.DIALS_CNT * (100);
successRateFromSince = Math.round(successRateFromSince);
if(isNaN(successRateFromSince)) {
successRateFromSince = 0;
}
console.log("Success rate since is " +successRateFromSince);
}
deferred.resolve(successRateFromSince);
});
},function (e) {
alert("ERROR: " + e.message);
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
return deferred.promise;
}
};
Place where error is occured:
// GET DATA IN ASSYNC TASK
DialsComputeService.computeSuccessRateSinceStart.then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
try{
row.SUCCESS_RATE_SINCE = result;
} catch (e) {
$ionicLoading.show({
template: $translate.instant('ERROR'),
duration:1000
});
}
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
// END GET DATA IN ASSYNC TASK
Your async function computeSuccessRateSinceStart is a function, so you need to call it as a function and pass it a row as a parameter:
DialsComputeService.computeSuccessRateSinceStart(yourRow).then( ... )
Once you do that, the return value from the function will be a promise, which has a then() method.