Getting error trying to start a new request while another is active in Vaadin 14 - vaadin-flow

Using Vaadin 14 I am facing the following error while I try to execute below code
UI current = UI.getCurrent();
Thread th = new Thread(() -> {
UI.setCurrent(current);
current.access(() -> {
//calling my service to save the data
current.push();
});
});
th.start();
I get this above error very rare but need to remove that as it shows in UI.

Related

nativescript-webview-interface event call back to app there is an issue - Migrating the pure Nativescript 5.x project to Nativescript 6

Using nativescript-webview-interface and event is registered to webview. Event is fired to app and it is working fine. But in nativescript 6 same code is not working.
var webViewInterfaceModule = require('nativescript-webview-interface');
exports.onWebViewLoaded = function(args) {
var webview = args.object;
oWebViewInterface = new webViewInterfaceModule.WebViewInterface(webview, buildSrc());
// where build source returns the html string
webview.on(webViewModule.WebView.loadFinishedEvent, (args) => {
//do something specific to app
});
oWebViewInterface.on("watchInc", (data) => {
console.log("event watchInc - want to do something app specific");
//not receiving this event
});
oWebViewInterface.on("watchEnd", (data) => {
console.log("event watchEnd - want to do something app specific");
//not receiving this event
}, 200); // Timeout needed as loading event is fired when nothing ready...
}
Thanks manoj. Moved to nativescript-webview-ext plugin and communication between webview and javascript is working fine.

In a Service Worker install listener, why does fetch return TypeError: Failed to fetch?

Using the sw-precache utility, I created a service worker that works if I refresh the page. But initially, the fetch call returns TypeError: Failed to fetch on a file which seems to cancel the rest. Refresh gets a few more files, refresh a few more times until all are fetched and then the service worker works fine. Each url loads fine, every time, even with the cache buster. All the calls are to https://localhost:9001 and are straight get calls. There are 17 total files.
Here is a code snippet:
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return setOfCachedUrls(cache).then(function(cachedUrls) {
return Promise.all(
Array.from(urlsToCacheKeys.values()).map(function(cacheKey) {
// If we don't have a key matching url in the cache already, add it.
if (!cachedUrls.has(cacheKey)) {
var request = new Request(cacheKey, {credentials: 'same-origin'});
return fetch(request).then(function(response) {
// Bail out of installation unless we get back a 200 OK for
// every request.
if (!response.ok) {
throw new Error('Request for ' + cacheKey + ' returned a ' +
'response with status ' + response.status);
}
return cleanResponse(response).then(function(responseToCache) {
return cache.put(cacheKey, responseToCache);
});
}).catch(function(e) {
throw new Error('fetch error: ' + e);
});
}
})
);
});
}).then(function() {
})
);
});
I tried adding keepalive:true,headers:{"Access-Control-Allow-Origin": "*"} to the Request but get the same result.
It seems the requests fail very soon, and I have seen the requests take a little more than a second to respond. Perhaps there is a way to set a timeout?
In the chrome dev tools network tab, it shows the failed attempts in red with a (canceled) status and the little service worker icon to the left.
It seems to work fine in FireFox. Chrome is having the trouble.

Error in Xamarin Android with a progress dialog “Only the original thread that created a view hierarchy can touch its views”

I'm trying to use a progress dialog, while filling a datagrid, but I get the following error: "Only the original thread that created a view hierarchy can touch its views", this is my code, i hope they can help me
public async void RelacionClientesREST()
{
try
{
var dlg = ProgressDialog.Show(this, "Loading", "Cargando relación de usuarios");
ThreadPool.QueueUserWorkItem(d => {
RestClient client = new RestClient("http://portalclientewa.azurewebsites.net/api/RelacionClientes/");
var request = new RestRequest("GetData", Method.GET);
request.Timeout = 1500000;
request.RequestFormat = DataFormat.Json;
request.AddParameter("idP", Idp);
var temp = client.Execute(request).Content;
var parsedJson = JsonConvert.DeserializeObject(temp).ToString();
var lst = JsonConvert.DeserializeObject<List<ClientesProp>>(parsedJson).ToList();
dataGrid.ItemsSource = lst;
RunOnUiThread(() => {
dlg.Dismiss();
});
});
}
catch (Exception ex)
{
Toast.MakeText(this, "No hay datos registrados", ToastLength.Short).Show();
}
}
The error is telling you the app's UI must be handled by the main thread. In your code, you are running some code on a background thread (ThreadPool.QueueUserWorkItem) that needs to be run on the UI thread (RunOnUiThread) instead.
you cannot use dlg.Dismiss(); inside ThreadPool.QueueUserWorkItem, move it before try close sign
why not use Task instead?
Task.Run(() => doStuff("hello world"));
It doesn't really seem a lot better, but at least it doesn't have an unused identifier.
Note: Task.Run() is .Net 4.5 or later. If you're using .Net 4 you have to do:
Task.Factory.StartNew(() => doStuff("hello world"));
Both of the above do use the thread pool.
Only the original thread that created a view hierarchy can touch its views
As #CaPorter said, the app's UI must be handled by the main thread. There are any number of ways to get code to execute on the UI thread, you could try using Looper.MainLooper with Handler.Post().
Modify your code like this :
ThreadPool.QueueUserWorkItem(d => {
...
Handler handler = new Handler(Looper.MainLooper);
Action action = () =>
{
dataGrid.ItemsSource = lst;
dlg.Dismiss();
};
handler.Post(action);
});

Ionic Prepopulated Database with Antair Cordova SQLitePlugin [help request]

____ INTRO
Hello everyone, first of all, three clarifications:
My english is not good, so I beg your pardon in advance for my mistakes,
I'm a newbie so forgive me for inaccuracies,
I have previously searched and tried the solutions I found on the internet but still I can not solve the problem of embedding a prepopulated database.
____ THE GOAL
I want to develop an app for iOS and Android with a prepopulated database.
Just for example, the database consists of 15.000 records each one made of three key-value pair (id, firstname and lastname).
___ WHAT I DID
Steps:
ionic start myapp blank
cd myapp
ionic platform add ios
ionic platform add android
Then I created an sqlite database for testing purpose, named mydb.sqlite, made of one table people containing two id, firstname, lastname records.
I decided to use the following plugin: https://github.com/Antair/Cordova-SQLitePlugin
That's because it can be installed with cordova tool.
ionic plugin add https://github.com/Antair/Cordova-SQLitePlugin
(Alert: I think that the instructions on the website show an incorrect reference - "cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin" - which refers to another plugin).
Then, following the instructions on the plugin website, I copied the database to myapp/www/db/ so that it can now be found at myapp/www/db/mydb.sqlite
I modified the index.html including the SQLite plugin just after the default app.js script:
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="SQLitePlugin.js"></script>
I also write some lines of code in index.html file to show a button:
<ion-content ng-controller="MyCtrl">
<button class="button" ng-click="all()">All</button>
</ion-content>
Finally I had modified ./js/app.js:
// Ionic Starter App
var db = null;
angular.module('starter', ['ionic' /* What goes here? */ ])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// some predefined code has been omitted
window.sqlitePlugin.importPrepopulatedDatabase({file: "mydb.sqlite", "importIfExists": true});
db = window.sqlitePlugin.openDatabase({name: "mydb.sqlite"});
}); // $ionicPlatform.ready
}) // .run
.controller('MyCtrl', function($scope){
$scope.all = function(){
var query = "SELECT * FROM people";
// I don't know how to proceed
}; // $scope.all
}); // .controller
___ THE PROBLEM
I don't know how to proceed in the controller section to query all the records (just an example of query) and show the results in the console.log.
I think that the following code must be completed in some way:
angular.module('starter', ['ionic' /* What goes here? */ ])
And also the code inside controller section must be completed:
$scope.all = function(){
var query = "SELECT * FROM people";
// I don't know how to proceed
}; // $scope.all
___ FINAL THANKS
Thank you in advance for the help you will give to me.
So this guy's code has helped a lot to encapsulate my DAL. I highly recommend that you use he's code pretty much verbatim.
https://gist.github.com/jgoux/10738978
You'll see he has the following method:
self.query = function(query, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function(transaction) {
transaction.executeSql(query, bindings, function(transaction, result) {
deferred.resolve(result);
}, function(transaction, error) {
deferred.reject(error);
});
});
return deferred.promise;
};
Let's break this down a bit. The query function takes a query string (the query param) and a list of possible bindings for ? in a query like "SELECT * FROM A_TABLE WHERE ID = ?". Because he's code is a service, the self value points to the service itself for all future invocations. The function will execute a transaction against the db, but it returns a promise that is only fulfilled once the db comes back.
His service provides a second helper function: fetchAll.
self.fetchAll = function(result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
fetchAll will read the rows in their entirety into an array. The result param for fetchAll is the result variable passed in the query function's promise fulfillment.
If you copy and paste his code into your service file, you now have a bonafide DB service. You can wrap that service up in a DAL. Here's an example from my project.
.service('LocationService', function ($q, DB, Util) {
'use strict';
var self = this;
self.locations = [];
self.loadLocked = false;
self.pending = [];
self.findLocations = function () {
var d = $q.defer();
if (self.locations.length > 0) {
d.resolve(self.locations);
}
else if (self.locations.length === 0 && !self.loadLocked) {
self.loadLocked = true;
DB.query("SELECT * FROM locations WHERE kind = 'active'")
.then(function (resultSet) {
var locations = DB.fetchAll(resultSet);
self.locations.
push.apply(self.locations, locations);
self.loadLocked = false;
d.resolve(self.locations);
self.pending.forEach(function (d) {
d.resolve(self.locations);
});
}, Util.handleError);
} else {
self.pending.push(d);
}
return d.promise;
};
})
This example is a bit noisy since it has some "threading" code to make sure if the same promise is fired twice it only runs against the DB once. The general poin is to show that the DB.query returns a promise. The "then" following the query method uses the DB service to fetchAll the data and add it into my local memory space. All of this is coordinated by the self.findLocations returning the variable d.promise.
Yours would behalf similarly. The controller could have your DAL service, like my LocationService, injected into it by AngularJS. If you're using the AngularJS UI, you can have it resolve the data and pass it into the list.
Finally, the only issue I have with the guy's code is that the db should come from this code.
var dbMaker = ($window.sqlitePlugin || $window);
The reason for this is that the plugin does not work within Apache Ripple. Since the plugin does a fine job mirroring the Web SQL interface of the browser, this simple little change will enable Ripple to run your Ionic Apps while still allowing you to work your SQLite in a real device.
I hope this helps.

Phonegap app won't reopen after close (Failed to load webpage with error: CDVWebViewDelegate: Navigation started when state=1)

I'm building an app for iOS using Phonegap and I've run into some problems. The app runs fine on both a simulator and real device until I close the app using the multi-tasking shutdown (double tap home button sequence..)
Upon reopening the app I find that it becomes unresponsive and you can't interact with it in any way. I've spent a fair amount of time trying to debug this and I've had no joy.
Error wise I have been getting the error Failed to load webpage with error: CDVWebViewDelegate: Navigation started when state=1 appear in the xcode console. After lots of googling it seems that this is caused due to hash tags within the URLs (something that I'm using for scrolling down to links both on the same and different pages). Most of the suggestions recommend updating phonegap/cordova to the latest version. I was previously on 2.8 and I went up to 2.9 and it still didn't work, i'm now on 3 and i'm still getting the same issues.
I've checked the cordova git and updated my CDVWebViewDelegate.m file several times with supposed fixes, nothing seems to work. I had a previous version of the app working on earlier versions of Cordova/Phonegap but I've recently upgraded and i'd rather not downgrade to get it to work..
I should probably note that I'm using zepto for my ajax calls and not JQM, for the hash tag scrolling i'm using the following code (figured this may help given it seems to be a hash issue..)
Hash Change function
// Ajax
var wrap = $('#contentScroller .scroller')
// get href
$('a.ajax').click(function () {
location.hash = $(this).attr('href').match(/(^.*)\./)[1]
return false
})
// load page
function hashChange() {
var page = location.hash.slice(1)
if (page != "" && window.location.hash) {
wrap.hide();
spinner.spin(target);
//setTimeout(function () {
wrap.load('pages/' + page + ".html .page-wrapper")
contentScroller.scrollTo(0,0);
refreshScroll();
//}, 1500);
snapper.close();
$(menuBtn).removeClass('active');
}else{
wrap.hide();
spinner.spin(target);
//setTimeout(function () {
wrap.load('pages/Welcome.html .page-wrapper')
refreshScroll();
//}, 1500);
snapper.close();
$(menuBtn).removeClass('active');
}
}
// check for hash change
if ("onhashchange" in window) {
$(window).on('hashchange', hashChange).trigger('hashchange')
} else { // lame browser
var lastHash = ''
setInterval(function () {
if (lastHash != location.hash)
hashChange()
lastHash = location.hash
contentScroller.scrollTo(0,0);
}, 100)
}
Scrolling
$(document)
.on('ajaxStart', function () {
wrap.hide();
})
.on('ajaxStop', function () {
//wrap.show();
})
.on('ajaxSuccess', function () {
//setTimeout(function () {
spinner.stop();
wrap.fadeIn(700);
refreshScroll();
//}, 1000);
// Local storage scrollTo
var storage = window.localStorage;
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('a.scroll-link').click(function (event) {
event.preventDefault();
url = url.replace('home.html?firstrun#', "");
url = url.replace(url, url+".html");
var myHref = $(this).attr('href');
if (url == myHref) {
var sameScroll = $(this).attr('data-scroll-same-page');
sameScroll = sameScroll.replace(sameScroll, "a#" + sameScroll);
contentScroller.scrollToElement(sameScroll, 1500);
} else {
var diffScroll = $(this).attr("data-scroll-diff-page");
storage.setItem("key", diffScroll);
//Alter value for iScroll
var value = window.localStorage.getItem("key");
value = value.replace(value, "a#" + value);
location.hash = $(this).attr('href').match(/(^.*)\./)[1]
$(window).on('hashchange', hashChange).trigger('hashchange')
// Scroll to element after .5 second
setTimeout(function () {
contentScroller.scrollToElement(value, 1500);
return false;
}, 2000)
// Clear local storage to prevent scrolling on page reload
localStorage.clear();
}
Sample link
<a href="IndexOfTerms.html" class="ajax scroll-link" data-scroll-diff-page="First_year_allowance">
this will then pass the attr "first_year_allowance" through to the IndexOfTerms pages and then scroll down to the element that has that id
Can anybody shed some light on how I might be able to fix this? It's really starting to annoy me so I'd quite like to get a fix pretty sharpish!
Note: Libraries used: iScroll, Zepto, fastclick, snapjs, spinjs
Thanks!

Resources