Search code examples
javascriptangularjsarrayscordovaphonegap-plugins

Cordova/Phonegap - Stock an array when I close the app (use them when I re-open)


I am using an array in my app. Something like that [{pseudo: "test", id: 0}, {pseudo: "Lucia", id: 2}]

I'd like to keep this array even when I close the app, how is it possible to do it ? Moreover I'd like to use them directly when I open the app (not when it is in background)

UPDATE: I tried with this,

stockage :

 var ami = ({
     idx: id
 });
 var ami_json = JSON.stringify(ami);
 sessionStorage.setItem("ami", ami_json);

lecture only launched the first time I open the app (I put it just after my controller started) but I got null value in console.log

var amiStorage = [];
var storageAmisNotifies = window.localStorage;
var ami_json = sessionStorage.getItem("ami");
var ami = JSON.parse(ami_json);

console.log(angular.toJson(ami));
console.log(ami);

amiStorage.push(ami);

console.log(amiStorage);
console.log(angular.toJson(amiStorage));

UPDATE 2 : $scope.isChecked is for ng-class, I'd like to take the id of my json but it is like [[{"pseudo": pseudo, "id": id}]] ... amisNotifies[i].id doesn't work

                var amisNotifies = [];
                $scope.isChecked = [];

                var storageAmisNotifies = window.localStorage;
                var ami_json = window.localStorage.getItem("info");
                var ami = JSON.parse(ami_json);

                if (ami != null){
                    amisNotifies.push(ami);
                    if (amisNotifies.length > 0) {
                                        for (var i = 0; i < amisNotifies.length; i++) {
                                            console.log(amisNotifies[[i]].id);
                                            $scope.isChecked[amisNotifies[i].id] = "fa fa-check-circle-o pull-right";
                                        }
                                    }
                }

Solution

  • Try using localStorage instead of sessionStorage

     var ami = ({
             idx: id
         });
         var ami_json = JSON.stringify(ami);
         window.localStorage.setItem("ami", ami_json);
    

    And also here

        var amiStorage = [];
        var storageAmisNotifies = window.localStorage;
        var ami_json = window.localStorage.getItem("ami");
        var ami = JSON.parse(ami_json);
    
        console.log(angular.toJson(ami));
        console.log(ami);
    
        amiStorage.push(ami);
    
        console.log(amiStorage);
        console.log(angular.toJson(amiStorage));