Reputation: 841
We have an application in Playstore which is developed using Cordova. Now we have rebuilt the total app in Native Android.
Now we want to upgrade the user from the previous app to the new app without logout.
For that, how to migrate local data of Cordova(window.localStorage) to Android shared preferences?
Upvotes: 1
Views: 920
Reputation: 841
Finally, I have migrated local data as follows
- In Activity/Fragment view add webView and
final WebView webView = findViewById(R.id.webView);
WebSettings webSetting = webView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
//set callback to get data from webview to Native
webView.addJavascriptInterface(new MyJavaScriptInterface(), "MyHandler");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
//Create HTML file to read stored data in webView local storage and pass it to Native
webView.loadUrl("file:///android_asset/readData.html");
- Create Class
MyJavaScriptInterface
to communicate between webView and native as follows
public class MyJavaScriptInterface {
@JavascriptInterface
public void sendKeyValue(String key, String value) {
Log.d("sendKeyValue", "key:" + key + " value:" + value);
}
}
In assets folder add following readData.html file
<html> <body> <div id="result"></div> <div id="resultCount"></div> <script> // Check browser support if (typeof(Storage) !== "undefined") { for(i = 0; i < localStorage.length; i++) { console.log("key "+i+" "+localStorage.key(i)); console.log("value"+i+" "+localStorage.key(i)+"= "+localStorage.getItem(localStorage.key(i))); window.MyHandler.sendKeyValue(localStorage.key(i), localStorage.getItem(localStorage.key(i))); } } </script> </body> </html>
Upvotes: 2
Reputation: 640
Use cordova-plugin-nativestorage.
It allows a simple yet native persistant method to save data in Android and iOS by natively implementing SharedPreferences in Android and NSDefault in iOS.
JavaScript:
cordova plugin add cordova-plugin-nativestorage
NativeStorage.setItem("username","kalidoss",setSuccess, setError);
function setSuccess(obj) {
alert(obj);
}
function setError(error) {
alert(error.code);
}
Java:
Context context =this;
String MyPREFERENCES = "NativeStorage";
SharedPreferences sharedpreferences = context.getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
String name= sharedpreferences.getString("username","");
Upvotes: 0