Coder Social home page Coder Social logo

thecocoaproject / cordova-plugin-nativestorage Goto Github PK

View Code? Open in Web Editor NEW
292.0 21.0 105.0 218 KB

Cordova plugin: Native storage of variables in Android, iOS and Windows

Home Page: http://thecocoaproject.github.io/

License: Apache License 2.0

Java 33.34% Objective-C 17.10% JavaScript 49.56%
cordova-plugin cordova-nativestorage ionic persistent-data storage android ios windows

cordova-plugin-nativestorage's Introduction

Cordova plugin NativeStorage

npm version Build Status Known Vulnerabilities

NPM

Join the chat for questions and updates Join the chat at https://gitter.im/TheCocoaProject/cordova-plugin-nativestorage


Cite this plugin:

@misc{callebautNS,
author =   {Gilles Callebaut and Alok Rajiv},
title =    {{NativeStorage - A Cordova Plugin}},
doi = {10.5281/zenodo.1312615},
howpublished = {\url{https://github.com/TheCocoaProject/cordova-plugin-nativestorage}},
}

You can also provide a version field to include a version number e.g., version = {2.3.1}.


:) As per npm-stat we just crossed 150k downloads!! Thanks to everyone who helped and to everyone who have send in their kind words!

NEW: Windows and OS X is supported! UPDATE: The Plugin can now also be found at the Telerik Plugin Market.

Documentation about the API prior to v2 can be found at the wiki


The plugin was created and developed by Gilles Callebaut, in the scope of an IWT/VlAIO Tetra project CrossMoS which assesses Mobile Cross-Platform Tools. This wouldn't be possible without the contributions of Alok Rajiv, our Cordova and JavaScript guru.

Please consider reading our wiki for more documentation about this plugin.

Contents

Why?

This plugin is created because of the non-persistent property of LocalStorage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.

Some complaints:

When to use the plugin

  • Simple: Uniform and convenient way of organizing, storing, and accessing the data
  • Fast: Less than 1 milisecond to save or retrieve an object (in general)
  • Persistence: Save data over multiple sessions, i.e. holds the data till the application is removed from the device
  • Small data: Store small amounts of persistent data (less than a few hundred kilobytes)
    • It is possible to store more than a few megabytes, but that's not the intended usage of the plugin.
    • See issue #31 for a more 'in-depth' explanation of size limit.

Examples

Storage of:

  • User preferences
  • Game progress
  • Text
  • ...

When not to use the plugin

  • Storing and retrieving files can be done by means of the file plugin
  • For storing many objects please consider trying a database-based strategy, for instance: WebSQL and SQLite plugin.

Scientific Articles

Assessment of Data Storage Strategies Using the Mobile Cross-Platform Tool Cordova

Installation

The plugin can be installed via the Cordova command line interface:

  • Navigate to the root folder for your Cordova/Phonegap/Ionic project.
  • Run the command:
cordova plugin add cordova-plugin-nativestorage

or through this git repo if you want to be running the development version:

cordova plugin add https://github.com/TheCocoaProject/cordova-plugin-nativestorage

If you're using ngCordova you can use the ngCordova-wrapper:

bower install git://github.com/TheCocoaProject/ngcordova-wrapper-nativestorage --save-dev

For more information about the usage of the plugin check the repo for the ngCordova-wrapper - Ionic V1. The plugin is also supported for Ionic, please check the official Ionic documentation for the installation procedure and use.

Reinstalling/installing developer version

Remove the plugin from the current project:

cordova plugin remove cordova-plugin-nativestorage

Install the developer version from Github:

cordova plugin add https://github.com/TheCocoaProject/cordova-plugin-nativestorage

Supported platforms

  • Android
  • iOS
  • Browser (for testing purposes)
  • Windows (thanks to Christian Helbig see PR)
  • OS X (thanks to Javier Ribó see PR)

Supported frameworks

Usage

The parameter of the success-callback function will be the saved or retrieved value, the error-callback will specify the occurred error.

Supported data types

As of version v2.0 all data types that can be stringified can be stored with the setItem and getItem method, see storing values. A more fine grained storage method is also provided. These methods can be used to store type-specific data types, see API prior to v2.

Storing values

NativeStorage.setItem("reference_to_value",<value>, <success-callback>, <error-callback>);

Retrieving values

NativeStorage.getItem("reference_to_value",<success-callback>, <error-callback>);

Retrieving all keys

NativeStorage.keys(<success-callback>, <error-callback>);

Removing values

Removing a single variable:

NativeStorage.remove("reference_to_value",<success-callback>, <error-callback>);

Removing all stored variables:

NativeStorage.clear(<success-callback>, <error-callback>);

iOS specific features

  • App Groups (share data between apps) First the suite name must be provided before accessing and retrieving data.
NativeStorage.initWithSuiteName("suitename");

Example

var app = {
    initialize: function () {
        this.bindEvents();
    },
    bindEvents: function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function () {
        var obj = {name: "NativeStorage", author: "GillesCallebaut"};

        // be certain to make an unique reference String for each variable!
        NativeStorage.setItem("reference", obj, this.setSuccess, this.setError);
    },
    setSuccess: function (obj) {
        console.log(obj.name);
        NativeStorage.getItem("reference", this.getSuccess, this.getError);
    },
    setError: function (error) {
        console.log(error.code);
        if (error.exception !== "") console.log(error.exception);
    },
    getSuccess: function (obj) {
        console.log(obj.name);
        NativeStorage.remove("reference", this.removeSuccess, this.removeError);
    },
    getError: function (error) {
        console.log(error.code);
        if (error.exception !== "") console.log(error.exception);
    },
    removeSuccess: function () {
        console.log("Removed");
    },
    removeError: function (error) {
        console.log(error.code);
        if (error.exception !== "") console.log(error.exception);
    }
};

app.initialize();

ngCordova (Ionic V1) example

var app = angular.module('starter.controllers', ['ngCordova.plugins.nativeStorage'])

app.controller('myCtrl', function ($ionicPlatform, $scope, $cordovaNativeStorage, $log) {
    $ionicPlatform.ready(function () {
        $scope.$apply(function () {
            $cordovaNativeStorage.setItem("ref", "value").then(function (value) {
                $log.log(value);
                $cordovaNativeStorage.getItem("ref").then(function (value) {
                    $log.log(value);
                }, function (error) {
                    $log.log(error);
                });
            }, function (error) {
                $log.log(error);
            });
        });
    });
});

Demo Example

A demo application can be found at cordova-plugin-nativestorage/examples/demo. This application will save a String when the SAVE (btn_load) is pushed. This String is the value which has been typed in the input field (data_input). When the LOAD button is pressed, the value is shown by means of an alert message.

Installation

  • Cloning the repo to a local dir
git clone https://github.com/GillesC/cordova-plugin-nativestorage.git
  • Navigating to the demo dir
cd cordova-plugin-nativestorage/examples/demo/
  • Adding target platforms
cordova platform add ios
cordova platform add android
cordova platform add browser
cordova platform add windows
  • Adding the plugin
cordova plugin add cordova-plugin-nativestorage
  • For testing the plugin
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-test-framework.git
cordova plugin add https://github.com/TheCocoaProject/cordova-plugin-nativestorage.git#:/tests
  • Run or emulate the demo application
cordova emulate ios
cordova run android
cordova run browser
cordova run windows

Security

Is it safe to store sensitive data via this plugin?

  • Yes and No, all stored values are only accessible by your application, which makes it safe. However, the values can be viewed when the attacker has access to your phone's password (e.g. lock-pattern) through an un-encrypted back-up on Android (if back-up is enabled) or through root-access. The latter is only possible if the phone is rooted. An extra encryption mechanism would be of value when an extra user-supplied password is used. This mode is on our Future Track list.

Errors

Error object contains:

  • code
  • source (= "Native"/"JS")
  • exception (if any, e.g. JSON exception)

Error codes

the code contains an integer whichs specifies the occurred error/problem

  • NATIVE_WRITE_FAILED = 1
  • ITEM_NOT_FOUND = 2
  • NULL_REFERENCE = 3
  • UNDEFINED_TYPE = 4
  • JSON_ERROR = 5
  • WRONG_PARAMETER = 6

Problems

If you encounter any problems, please remove the current plugin and re-add it. This will install the latest version.

If you have code issues, things not related to a bug of the plugin please consider posting your question on Stackoverflow. And add our own tag, cordova-nativestorage.

  • Be certain to only retrieve a saved value when the put/set success-callback method was invoked.
  • When using Ionic V1 the plugin can be undefined, the solution was descibed in issue #10:
    • Remove ng-app from body
    • put this code at the end of index.html:
    • <script type="text/javascript"> document.addEventListener('deviceready', function onDeviceReady() { angular.bootstrap(document.querySelector('body'), ['starter']); }, false); </script>
  • Unknown provider: $cordovaNativeStorageProvider
    • Are you certain you've included the wrapper?
  • Failed to instantiate module ngCordova.plugins.nativeStorage
  • Module 'ngCordova.plugins.nativeStorage' is not available
    • Check your bower json file (bower.json) to see if everything is correct
    • be certain that the wrappers js file is included as described in the README of the wrapper
  • Plugin doesn't seem to work in iOS 10
    • Solution is presented on Stackoverflow in this thread. The issue was also discussed in issue #36.

F.A.Q.

  • Is data persistent between app updates?
    • Yes. The data should persistent till the app has been deleted from the device. This because the plugin uses Sharedpreferences in Android and NSUserDefaults in iOS.
  • Oh no my stored data is not cleared after reinstalling my application. How do I resolve this 'issue'?
  • What database are you using and why?
    • None. The plugin uses Sharedpreferences in Android and NSUserDefaults in iOS. These strategies are designed for storing data quick and easy. See the usage of the plugin for more info about DB vs NativeStorage.
  • Is it possible to save images and audio with the plugin?
    • Yes. If you could stringify the data. Should I save imaged and audio is a different question. If the provided data isn't large and there isn't need to store a large amount of it, it will be OK. See the usage of the plugin for more info about storing large data with the plugin.
  • Is there a forum where people interested in the plugin could discuss issues like this?
  • Can I access the saved value in Android?
  • Can I access saved values in JavaScript?
  • Does this plugin supports Cordova 3.9.2?

Applications using this plugin

If you're utilizing this plugin and wish to add your application to this readme, please contact me.

cordova-plugin-nativestorage's People

Contributors

alokrajiv avatar beaulac avatar danielsogl avatar dotnetcarpenter avatar gillesc avatar gitter-badger avatar janpio avatar kiwi-josh avatar kmyllyvi avatar korsgaard avatar soyangel avatar ulesta avatar ydeshayes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-nativestorage's Issues

Uncaught ReferenceError: NativeStorage is not defined, http://localhost:8100/lib/ionic/js/ioni c.bundle.js, Line: 17946

I have tried the script in the body

<script type="text/javascript"> angular.element(document).ready(function () { if (window.cordova) { console.log("Running in Cordova, will bootstrap AngularJS once 'deviceready' event fires."); document.addEventListener('deviceready', function () { console.log("Deviceready event has fired, bootstrapping AngularJS."); angular.bootstrap(document.querySelector('body'), ['starter']); }, false); } else { console.log("Running in browser, bootstrapping AngularJS now."); angular.bootstrap(document.body, ['starter']); } }); </script>

it is working for Android but IOS i am getting that Uncaught ReferenceError: NativeStorage is not defined. I am using xcode 7.3.1 and cordova 6.3.0.

NativeStorage.clear()?

hey there
i think a window.NativeStorage.clear() would make sense to have. what do you think?
cheers

Possibility to use add browser environment support?

I am currently using LocalStorage in an Ionic 2 app and was planning to use NativeStorage instead.
But the plugin does not work in the browser, so the development broke up using ionic serve and I guess it won't work too if I try to use my app as a "progressive web app".

Is it any plan to add support for the browser environment, maybe using as a layer above the browser localstorage? Does it make any sense?

[]s!

Is secure?

Can i save the username and password with this DB ? Can others apps see the user data ?

Can't set item while in NativeStorage callback

Please let me know if this is intended behavior, but I didn't see any docs. I want to get the result of an item, and then set different items based on that value. Here's the code I'm using:

NativeStorage.getItem("oldestNewPerk", function (oldNew) {
                serverapi.getRecentPerkInfo(oldNew).done(function (data) {
                    console.log("First id: " + data.first_id + " , count: " + data.count)
                    NativeStorage.setItem("oldestNewPerk", data.first_id, null, function (err) {
                        console.log(err);
                    })
// ... etc

Every time I do this, I get this error from setting the item:

// xcode
{"code":5,"source":"JS","exception":{"line":284,"column":14,"sourceURL":"file:///private/var/mobile/Containers/Bundle/Application/7DFD3A58-04CB-4816-B996-A626C03100FF/DiscountMeIn.app/www/plugins/cordova-plugin-nativestorage/www/mainHandle.js"}}
// safari
TypeError: undefined is not a function (evaluating 'error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err))')

Happy to elaborate more if necessary, but I can't use this plugin without this being handled.

Failed to install

Hello,

i get the following error, when i install the plugin, what can i do?

AdminisorsiMac6:Pushsafer admin$ cordova plugin add cordova-plugin-nativestorage
Installing "cordova-plugin-nativestorage" for android
ANDROID_HOME=/Users/admin/Documents/adt-bundle/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home
Subproject Path: CordovaLib

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugApk'.
   > A problem occurred configuring project ':CordovaLib'.
      > Could not resolve all dependencies for configuration ':CordovaLib:class path'
         > Could not find com.android.tools.build:grade:2.2.2..
           Searched in the following locations:
               https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.2/gradle-2.2.2.pom
               https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.2/gradle-2.2.2.jar
           Required by:
               android:CordovaLib:unspecified

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.333 secs
Failed to install 'cordova-plugin-nativestorage':Error: /Users/admin/Documents/Pushsafer/platforms/android/gradlew: Command failed with exit code 1
    at ChildProcess.whenDone (/Users/admin/Documents/Pushsafer/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:169:23)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
Error: /Users/admin/Documents/Pushsafer/platforms/android/gradlew: Command failed with exit code 1
AdminisorsiMac6:Pushsafer admin$

Kevin

Implement Web fallback when cordova is not available

Now if cordova is not available the plugin throws the plugin_not_installed error.

Since this plugin has a small API, it would be easy to add a proper web fallback for browsers:

  getPromisifiedLocalStorage() {
    return {
        setItem: (key, value) => {
          return new Promise( (resolve, reject) => {
            try {
              window.localStorage.setItem(key, this.encodePayload(value));
              resolve();
            } catch (error) {
              reject(error);
            }
          });
        },
        getItem: (key) => {
          return new Promise( (resolve, reject) => {
            try {
              const result = window.localStorage.getItem(key);
              resolve(this.decodePayload(result));
            } catch (error) {
              reject(error);
            }
          });
        },
        remove: (key) => {
          return new Promise( (resolve, reject) => {
            try {
              window.localStorage.removeItem(key);
              resolve();
            } catch (error) {
              reject(error);
            }
          });
        },
        clear: () => {
          return new Promise( (resolve, reject) => {
            try {
              window.localStorage.clear();
              resolve();
            } catch (error) {
              reject(error);
            }
          });
        },
      }

Note: This implementation is Promise based as I use Ionic-Native, but its pretty straight forward to make rewrite it into callbacks.

NativeStorageError code on browser is another NativeStorageError not an Integer as expected

Hey,

I upgraded from 2.0.2 to the latest version 2.2.1 and I'm encountering a problem in the browser. When I get an error (e.g. not found) the error looks like:
screen shot 2017-02-20 at 10 19 20

Previously the error code would be an Integer. From what I can see in the iOS version it also returns an Integer. I had a look through your commits and it seems your fix to issue #40 is the reason for this issue.

Is it a bug or am I missing something?

Thanks,
Alex

callbacks don't seem to work on iOS 10 beta 7

First I wanted to thank you for the awesome plugin 😄

On iOS 10 (beta 7) the global NativeStorage Object is accessible, along with all documented methods. Unfortunately none of the callbacks get executed.

This example code works in iOS 9 but gives no output whatsoever (web Inspector, xcode console) in iOS 10:

NativeStorage.setItem('sample', 'abc', function () {console.log(arguments)}, function () {console.log(arguments)})

I know it's still beta but do you plan on adding iOS 10 support?

Access stored values in Android

Variables can be accessed in Android by using the getString method provided by SharedPreferences. If NativeStorage API is used prior to v2.0 you need to use getBoolean, getString, getDouble,... corresponding to the variable type you have stored in JavaScript.

An Android snippet can be found here:

private static final String PREFS_NAME = "NativeStorage";
private static final String KEY= "reference_to_var";
String value = getValue(Activity.this, KEY , null);
      

String getValue(Context context, String key, String defaultValue) {
   SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
   return settings.getString(key, defaultValue);
}

It is important that you use "NativeStorage" as the name of the preferences.

Question on StackOverflow.
Question on Github

GetNativeStorage from Java

Hello,

can someone help me!
I save some data with this plugin. Now i want to read out the data from Java.
I created a widget and want use the stored data!

This ist the widget java source:

package de.appzer.Pushsafer;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;
import android.widget.Toast;

import static android.content.Context.MODE_PRIVATE;
import static de.appzer.Pushsafer.R.layout.pushsafer_widget;

/**
 * Implementation of App Widget functionality.
 */
public class PushsaferWidget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), pushsafer_widget);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }

        for(int j = 0; j < appWidgetIds.length; j++)
        {
            int appWidgetId = appWidgetIds[j];

            try {
                Intent intent = new Intent("android.intent.action.MAIN");
                intent.addCategory("android.intent.category.LAUNCHER");

                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.setComponent(new ComponentName(context.getPackageName(), MainActivity.class.getName()));
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        context, 0, intent, 0);
                RemoteViews views = new RemoteViews(context.getPackageName(), pushsafer_widget);
                views.setOnClickPendingIntent(R.id.button, pendingIntent);
                appWidgetManager.updateAppWidget(appWidgetId, views);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(context.getApplicationContext(),
                        "There was a problem loading the application: ",
                        Toast.LENGTH_SHORT).show();
            }

        }

        SharedPreferences sharedPreferences = context.getSharedPreferences("MainActivity", MODE_PRIVATE);
        System.out.println("********---------    shared pref values...   " +  sharedPreferences.getString("native-messages", "no value"));

    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}

This code do nothing

SharedPreferences sharedPreferences = context.getSharedPreferences("MainActivity", MODE_PRIVATE);
        System.out.println("********---------    shared pref values...   " +  sharedPreferences.getString("native-messages", "no value"));

native-messages = is the stored var

Thanks
kevin

Doesnt compile for iOS with cordova-ios < 4

I get compile errors on ios:

cordova-plugin-nativestorage/NativeStorage.m:45:8: warning: 
      incompatible pointer to integer conversion initializing 'BOOL' (aka 'signed char') with an expression of type 'id' [-Wint-conversion]
                BOOL aBoolean = [command.arguments objectAtIndex:1];
                     ^          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cordova-plugin-nativestorage/NativeStorage.m:93:48: error: 
      no known class method for selector 'resultWithStatus:messageAsNSInteger:'
                        if(success) pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsNSInteger:anInt];
                                                                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cordova-plugin-nativestorage/NativeStorage.m:112:36: error: 
      no known class method for selector 'resultWithStatus:messageAsNSInteger:'
                        pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsNSInteger:anInt];
                                                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning and 2 errors generated.

Is compatibility possible with cordova iOS < 4? I need iOS 7 support.

Android Entries Not Cleared

I've noticed that recently the NativeStorage entries are not being cleared after uninstalling the app. Looking at the NativeStorage github, it seems like android is using Sharedpreferences.

I googled similar issues and it seems like, we have to set android:allowBackup=false in the application tag of AndroidManifest.xml.

Currently, my application tag looks like this:
<application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">

JSON_ERROR

Hi

I'm having a weird error when retrieving some data with NativeStorage.getItem().

The data is retrieved ok at first instance, but afterwards some millisenconds later the error callback is called with an error code 5.

When I log the data in Android it seems the json is cut, logcat doesn't show the whole JSON.

The data is less than 100KB...

Any idea what might be happening?

when use nativestorage in ionic2, and compile for android,show " java.lang.NoClassDefFoundError: NativeStorage",put the NativeStorage.java to a package fix it.

10-20 14:55:55.890 31013-31013/com W/System.err﹕ Caused by: java.lang.NoClassDefFoundError: NativeStorage
10-20 14:55:55.890 31013-31013/com W/System.err﹕ ... 18 more
10-20 14:55:55.890 31013-31013/com W/System.err﹕ Caused by: java.lang.ClassNotFoundException: NativeStorage
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ ... 18 more
10-20 14:55:55.890 31013-31013/com I/System.out﹕ Error adding plugin NativeStorage.
10-20 14:55:55.890 31013-31013/com W/System.err﹕ java.lang.NullPointerException
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at org.apache.cordova.PluginManager.getPlugin(PluginManager.java:172)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at org.apache.cordova.PluginManager.exec(PluginManager.java:123)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at org.apache.cordova.CordovaBridge.jsExec(CordovaBridge.java:59)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at org.apache.cordova.CordovaBridge.promptOnJsPrompt(CordovaBridge.java:135)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at org.apache.cordova.engine.SystemWebChromeClient.onJsPrompt(SystemWebChromeClient.java:124)
10-20 14:55:55.890 31013-31013/com W/System.err﹕ at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:681)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4829)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
10-20 14:55:55.900 31013-31013/com W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ java.lang.ClassNotFoundException: NativeStorage
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at java.lang.Class.classForName(Native Method)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at java.lang.Class.forName(Class.java:217)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at java.lang.Class.forName(Class.java:172)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at org.apache.cordova.PluginManager.instantiatePlugin(PluginManager.java:490)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at org.apache.cordova.PluginManager.getPlugin(PluginManager.java:170)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at org.apache.cordova.PluginManager.exec(PluginManager.java:123)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at org.apache.cordova.CordovaBridge.jsExec(CordovaBridge.java:59)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at org.apache.cordova.CordovaBridge.promptOnJsPrompt(CordovaBridge.java:135)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at org.apache.cordova.engine.SystemWebChromeClient.onJsPrompt(SystemWebChromeClient.java:124)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:681)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4829)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
10-20 14:55:55.910 31013-31013/com W/System.err﹕ Caused by: java.lang.NoClassDefFoundError: NativeStorage
10-20 14:55:55.920 31013-31013/com W/System.err﹕ ... 18 more

NativeStorage is unavailable/undefined

I installed the Plugin, but it is not working.
nativeStorage is not available.

I try on deviceready:

var ns = (typeof nativeStorage == "undefined") ? false : true;
if(ns)
{
    alert("nativeStorage is available");
    nativeStorage.putString(
        "foo",
        "bar",
        function(result)
        {
            alert(result);
         },
         function(e)
         {
            alert(e);
         }
    );
    nativeStorage.getString(
        "bla",
        function(result)
        {
            alert(result);
        },
        function(e)
        {
            alert(e);
        }
    );
}

any ideas? I am using phonegap actual

error.code undefined

Sorry to be nuisance, but I was hoping to do an insert when no object is found through the error.code API you provided in your documentation.

It's however returning me a string. Will there be a future update to make this available by any chance?

Why Async ?

Thanks for writing this plugin.
For iOS, NSUserDefaults is synchronous.
Why are we using $cordovaNativeStorage.getItem and $cordovaNativeStorage.setItem with callback/promises ?
Won't it be synchronous ?

Error in getting item

So after trying to use get item I get this error

Error in Success callbackId: NativeStorage742808021 : TypeError: error is not a function on line 312 of cordova.js

and Uncaught TypeError: error is not a function on line 314 of cordova.js

Then if I use getItem again, it returns error code 5 and also has the same error on line 312 and 314 of cordova js.

Thank you for your time.

Consistent storage growth using NativeStorage on iOS with no apparent reason

We converted our app from using localStorage to using native-storage after hearing from users with low-memory devices. Everything works well, function-wise, but we have noticed that there is a consistent storage increase every time we log into the app - for no apparent reason (iOS 10.1.1 iPhone 6S). We noticed about 1MB of storage for every login operation. During the login our app reads all the data we have in native-storage to memory (up to 100 keys at most) - and over-writes 3 keys - the size of all 100 keys including names, data - is much less than 1MB - and the 3 keys that are written are much less that 1KB.

Despite that - the storage taken by the App continue to grow - for no apparent reason. We have noticed somewhat similar situation in Android - there the growth seems smaller - and after a while the stored data seems to be truncated to a smaller size - so maybe it is using a cache that is cleared after a while in Android (and not in iOS).

Is there anything we can do to eliminate this behavior - either in code or in compile/build option?

Calling clear() make the application crash on ios

Hello,

My app crash when I call clear().

Iphone SE simulator, ios 10.2, cordova 6.4.0

My JS code:

export function clear(callback = () => {}) {
  return new Promise(
    (resolve, reject) =>
      NativeStorage.clear(() => {
        resolve();
        callback();
      }, (err) => {
        reject(err);
        callback(err);
      })
  );
}

The stack:

Jan 10 09:21:55 MBP-de-Yann Stryng[5966]: [User Defaults] Attempt to set a non-property-list object <null> as an NSUserDefaults/CFPreferences value for key token
Jan 10 09:21:55 MBP-de-Yann Stryng[5966]: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object null for key token'
	*** First throw call stack:
	(
		0   CoreFoundation                      0x0000000100e7fd4b __exceptionPreprocess + 171
		1   libobjc.A.dylib                     0x00000001008b821e objc_exception_throw + 48
		2   CoreFoundation                      0x0000000100ee92b5 +[NSException raise:format:] + 197
		3   CoreFoundation                      0x0000000100dcff3b _CFPrefsValidateValueForKey + 267
		4   CoreFoundation                      0x0000000100eea843 -[CFPrefsPlistSource alreadylocked_setValues:forKeys:count:] + 259
		5   CoreFoundation                      0x0000000100ea7648 -[CFPrefsSource setValues:forKeys:count:removeValuesForKeys:count:] + 264
		6   CoreFoundation                      0x0000000100dcfe20 -[CFPrefsSource setValues:forKeys:count:] + 32
		7   CoreFoundation                      0x0000000100ee17c9 -[CFPrefsSearchListSource alreadylocked_setValues:forKeys:count:] + 473
		8   CoreFoundation                      0x0000000100ea7648 -[CFPrefsSource setValues:forKeys:count:removeValuesForKeys:count:] + 264
		9   CoreFoundation                      0x0000000100dcfe20 -[CFPrefsSource setValues:forKeys:count:] + 32
		10  CoreFoundation                      0x0000000100e1499a -[CFPrefsSource setValue:forKey:] + 58
		11  CoreFoundation                      0x0000000100ee3702 __108-[_CFXPreferences(SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:]_block_invoke + 322
		12  CoreFoundation                      0x0000000100ee2f09 normalizeQuintuplet + 329
		13  CoreFoundation                      0x0000000100ee35b8 -[_CFXPreferences(SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:] + 104
		14  CoreFoundation                      0x0000000100ecdc95 -[_CFXPreferences setValue:forKey:appIdentifier:container:configurationURL:] + 261
		15  CoreFoundation                      0x0000000100e148e4 _CFPreferencesSetAppValueWithContainer + 68
		16  Foundation                          0x00000001003afc96 -[NSUserDefaults(NSUserDefaults) setObject:forKey:] + 55
		17  Stryng                              0x00000001002b3122 __25-[NativeStorage setItem:]_block_invoke + 290
		18  libdispatch.dylib                   0x0000000104411808 _dispatch_call_block_and_release + 12
		19  libdispatch.dylib                   0x000000010443312e _dispatch_client_callout + 8
		20  libdispatch.dylib                   0x00000001044191f8 _dispatch_queue_override_invoke + 809
		21  libdispatch.dylib                   0x000000010441a9dc _dispatch_root_queue_drain + 506
		22  libdispatch.dylib                   0x000000010441a782 _dispatch_worker_thread3 + 113
		23  libsystem_pthread.dylib             0x00000001047d8746 _pthread_wqthread + 1299
		24  libsystem_pthread.dylib             0x00000001047d8221 start_wqthread + 13
	)
Jan 10 09:21:55 MBP-de-Yann SpringBoard[88084]: [KeyboardArbiter] HW kbd: Failed to set (null) as keyboard focus
Jan 10 09:21:55 MBP-de-Yann com.apple.CoreSimulator.SimDevice.6477C956-D87C-41C9-9FD0-1FB502D13465.launchd_sim[88068] (UIKitApplication:com.app.stryng[0x4978][5966]): Service exited due to Abort trap: 6
Jan 10 09:21:55 MBP-de-Yann backboardd[88086]: [Common] Unable to get short BSD proc info for 5966: No such process
Jan 10 09:21:55 MBP-de-Yann backboardd[88086]: [Common] Unable to get proc info for 5966: No such process
Jan 10 09:21:56 MBP-de-Yann assertiond[88089]: notify_suspend_pid() failed with error 7
Jan 10 09:21:56 MBP-de-Yann watchlistd[88161]: Now playing app did change to '(null)' (playing: 0) from '(null)'
Jan 10 09:21:56 MBP-de-Yann watchlistd[88161]: WLKPlaybackSummary - Parameter failed validation bundleID. It is nil

Thanks for your help

Supplied parameters do not match any signature of call target

I have an ionic2 app with NativeStorage plugin and I'm following the instructions for storing values as shown below. However, I get a Typescript error and it won't let me build the app

import { NativeStorage } from 'ionic-native';

setUsername(storageemail) {
  NativeStorage.setItem('storageemail',storageemail, this.setSuccess(), this.setError());
}
setSuccess(obj) {
  console.log(obj.name);
};
setError(error) {
  console.log(error.code);
  if (error.exception !== "") console.log(error.exception);
};

Error

[ts] Supplied parameters do not match any signature of call target.
(method) NativeStorage.setItem(reference: string, value: any): Promise<any>
Stores a value

Details

Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.13
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.46
ios-deploy version: Not installed
ios-sim version: 4.1.1
OS: OS X El Capitan
Node Version: v6.3.1
Xcode version: Xcode 8.1 Build version 8B62

Package.json

{
  "name": "MoneyLeash",
  "author": "Luis Cabrera",
  "homepage": "http://moneyleash.com/",
  "private": true,
  "repository": {
    "type": "git",
    "url": "https://github.com/gigocabrera/MoneyLeash2"
  },
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic/storage": "1.1.6",
    "angularfire2": "^2.0.0-beta.6",
    "firebase": "3.3.0",
    "font-awesome": "^4.6.3",
    "ionic-angular": "^2.0.0-rc.3",
    "ionic-native": "^2.2.7",
    "ionicons": "3.0.0",
    "moment": "^2.15.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "^0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "0.0.46",
    "@types/request": "0.0.30",
    "typescript": "^2.0.9"
  },
  "description": "Don't let your money run wild. Keep it on a leash!",
  "cordovaPlugins": [
    "cordoba-plugin-device",
    "cordoba-plugin-console",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-statusbar",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "config": {
    "ionic_copy": "./scripts/copy-custom-libs.js"
  }
}

Uncaught ReferenceError: require is not defined

When I launch my app in console I get "Uncaught ReferenceError: require is not defined" from NativeStorage.js.

And when I try to set, for example, string I get "Uncaught TypeError: NativeStorage.putString is not a function".

What should I do?

SyntaxError: Unexpected token when I call NativeStorage.getItem

Hi,
private void cordovaPreference() {
// Log.i("jimmy","url"+url);

    SharedPreferences mySharedPreferences = getSharedPreferences(PREFS_NAME, Activity.MODE_WORLD_READABLE);

    SharedPreferences.Editor editor = mySharedPreferences.edit();
    editor.putString("reference", "12342345fasdfaf");

    editor.commit();
}

I store the reference in android
Then I get it from ionic side.
NativeStorage.getItem("reference")
.then(
data=>console.log("nativestoragesuccess"+data),
error=>console.error("nativestorageerror"+error.exception)
);
The strange thing is that when I put "reference", "12342345" or the value is just num. It's ok But editor.putString("reference", "12342345fasdfaf") or any value contains a-z .It show SyntaxError: Unexpected token f .I don't get it

Problem with Android 5.0.1 and iOS 9

Thank you for this plugin, works great. There is a small issue on some platforms though.
I'm getting an error on both iOS 9 and Android 5.0.1 concerning the LocalStorageHandle.

I've attached screenshots to show where it goes wrong. Do you have any idea how to solve these?

iOS 9
screen shot 2017-03-08 at 16 43 53

Android 5.0.1
screen shot 2017-03-08 at 16 47 47

Thanks in advance!

Limit On String Size

Is there a limit on how large an object/string can be for it to be successfully saved? Also, could error code 1 " native write failed" imply that the device is out of memory?

$cordovaNativeStorage.clear is not a function

Error when calling NativeStorage.clear:

Uncaught TypeError: $cordovaNativeStorage.clear is not a function

    console.log($cordovaNativeStorage); // 3 methods - get, set, and remove. does not include clear. 
    var deferred = $q.defer();
    $cordovaNativeStorage.clear(function() { // throws 
      console.log('storage: cleared')
      deferred.resolve()
    }, function(err) {
      console.log(err);
    })
    return deferred.promise;

Help with android SharedPreferences.

Hello,
I need to read string variable from javascript code, which I need to set from android Native code.
`
public static final String PREFS_NAME = "NativeStorage";
public static final String REFFERER = "refferer";

     SharedPreferences mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

      Editor edit = mPrefs.edit();
	  edit.putString(REFFERER, referrerString);
	  edit.commit();` 

Getting this from javascript returns null
NativeStorage.getString("refferer",function(result), function(err)

Any advices, how to put string in android java and get it from javascript NativeStorage, highly appreciate.

Issue with plugin version

Hi,
There is something strange happening with the plugin version. I use cordova-check-plugins which returns that the latest version of this plugin is 2.1.0. I also see this version being reported in the npm site however everytime I run cordova plugin add cordova-plugin-nativestorage and then cordova plugin list, the version of it is 2.0.2.

Put getItem inner another function

Hey,

I want to add it inner another function. Because I call getItem many time in my project. Sample my code as (I use angularjs and phonegap):
$rootScope.getCookie = function (_name) {
$cordovaNativeStorage.getItem(_name).then(function (value) {
console.log('statement 1');
});
}
var globals = $rootScope.getCookie('globals');
console.log('statement 2');
=> result on firebug's console: 'statement 2' appear before 'statement 1'.

I want 'statement 1' appear before 'statement 2'. Is it possible to do?

Please support me. Thanks.

Uncaught TypeError: error is not a function

Hey,

Using Cordova on Windows 10/Browser. Getting a "Uncaught TypeError: error is not a function" error at mainHandle.js:87.

The line throwing the error is:
error("The type isn't supported or isn't been recognized");

I'm using Windows 10, Chrome 54, JQuery 3.1.1, Cordova 6.3.1, Android 5.2.2, Browser 4.1.0

Adding a generic
function error(e) { console.log(e); }
doesn't work :/

inconsistent error on browser

When getting an error on the browser platform, the result is an integer (or maybe a string) instead of a NativeStorageError.

sync writes in Android

Noticed that you use apply() followed by callbackContext.
Would it be better to use commit() and then return the value, because if multiple threads or simultaneous writes come, apply() is async and not blocking. Also there is no provision for getting response whether the write is complete in the callback.

Get all keys for items in storage?

I'm storing a bunch of saved projects on an app I'm working on. When the user boots up I want to get all of their projects and list them. Previously I was saving the projects as JSON (stringified) to localStorage and pulling them out when the app booted up e.g:

for(var key in localStorage) {
    ...
}

I can't see a way to do something similar with NativeStorage. Would you suggest keeping an index in storage e.g. "project_ids" instead?

Thanks,
Alex

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.