ClassNotFoundException in NativeScript using .extend() - javascript

I am trying to extend GoogleApiClient.ConnectionCallbacks(), but keep getting an error
`java.lang.RuntimeException: Unable to start activity
ComponentInfo{org.nativescript.sampleGroceries/com.tns.NativeScriptActivity}:
com.tns.NativeScriptException: Calling js method onCreate failed
Error calling module function
Error: java.lang.ClassNotFoundException:
com.google.android.gms.common.api.GoogleApiClient_ConnectionCallbacks
java.lang.Class.classForName(Native Method)
java.lang.Class.forName(Class.java:324)
java.lang.Class.forName(Class.java:285)
com.tns.DexFactory.generateDex(DexFactory.java:262)
com.tns.DexFactory.resolveClass(DexFactory.java:120)
com.tns.ClassResolver.resolveClass(ClassResolver.java:45)
`
My corresponding code is
var GoogleApiClient = com.google.android.gms.common.api.GoogleApiClient;
var myConnectionCallbacks = GoogleApiClient.ConnectionCallbacks.extend({
onConnected: function(connectionHint){
var MessageListener = MessageListener.extend({
onFound: function(message){
Log.d("MESSAGE", "Found message :) ");
},
onLost: function(message){
Log.d("MESSAGE", "Lost message :( ");
}
});
var mMessageListener = new MessageListener();
},
onConnectionSuspended: function(){}
});
var MessagesOptionsBuilder = new com.google.android.gms.nearby.messages.MessagesOptions.Builder().setPermissions(NearbyPermissions.BLE).build();
var test = new GoogleApiClient.Builder(context).addApi(Nearby.MESSAGES_API, MessagesOptionsBuilder);
test.addConnectionCallbacks(new myConnectionCallbacks(this));
Maybe I misunderstood the Docs?
https://docs.nativescript.org/runtimes/android/generator/extend-class-interface
Edit: Why is there an underscore in the error log after GoogleApiClient?
Any suggestions what I do wrong?

The problem here is your are trying to extend an interface which is wrong . More info -> https://docs.nativescript.org/runtimes/android/generator/extend-class-interface#interfaces
var MessagesOptionsBuilder = new com.google.android.gms.nearby.messages.MessagesOptions.Builder().setPermissions(NearbyPermissions.BLE).build();
var test = new GoogleApiClient.Builder(context).addApi(Nearby.MESSAGES_API, MessagesOptionsBuilder);
test.addConnectionCallbacks(new com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks({
onConnected: function (connectionHint) {
var MessageListener = MessageListener.extend({
onFound: function (message) {
console.log(Found message :) ");
},
onLost: function (message) {
console.log("Lost message :( ");
}
});
var mMessageListener = new MessageListener();
},
onConnectionSuspended: function () { }
}));
and just incase the MessageListener is an interface the just remove the .extend
var MessagesOptionsBuilder = new com.google.android.gms.nearby.messages.MessagesOptions.Builder().setPermissions(NearbyPermissions.BLE).build();
var test = new GoogleApiClient.Builder(context).addApi(Nearby.MESSAGES_API, MessagesOptionsBuilder);
test.addConnectionCallbacks(new com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks({
onConnected: function (connectionHint) {
new MessageListener({
onFound: function (message) {
console.log(Found message :) ");
},
onLost: function (message) {
console.log("Lost message :( ");
}
});
},
onConnectionSuspended: function () { }
}));

Related

Unhandled expression at line :

So i am playing around with Babylon. In a createScene function I am also loading the AssetManager.
Whenever i add a task, it will throw errors: unhandled expression 1 for every line of my HTML document.
This also happens, if I ignore my assetManager and put in SceneLoader.ImportMesh instead.
I really dont know what to do anymore.
Thats my assetManager:
function assetManager() {
var assetsManager = new BABYLON.AssetsManager(scene);
var meshTask = assetsManager.addMeshTask("baum", "", "assets/", "carAcura.obj");
meshTask.onSuccess = function (task) {
task.loadedMeshes[0].position = BABYLON.Vector3.Zero();
engine.loadingUIText = "Loaded asset " + task.loadedMeshes[0].name;
console.log(task.loadedMeshes[0].name);
}
assetsManager.onTaskError = function (task) {
console.log("error on Loading" + task.name);
}
assetsManager.load();
assetsManager.onFinish = function (tasks) {
console.log("done");
engine.runRenderLoop(function () {
if (engine.webGLVersion === 1) {
pixiRenderer.reset();
}
scene.render();
engine.wipeCaches(true);
pixiRenderer.reset();
pixiRenderer.render(stage);
divFps.innerHTML = engine.getFps().toFixed() + " FPS";
//loop();
});
};
};

node js self this call method

I'm working on NodeJS and I have this module:
Manager.js
with this code (this is not all the code...):
//
// Object Manager
function Manager(params) {
client = new ModbusRTU();
}
//connessione alla seriale per lettura modbus
Manager.prototype.connectClient = function(){
// try to connect
client.connectRTUBuffered ("/dev/ttyS3", { baudRate: 19200 })
.then(function()
{
mbsState = MBS_STATE_GOOD_CONNECT;
mbsStatus = "Connected, wait for reading...";
console.log(mbsStatus);
})
.catch(function(e)
{
mbsState = MBS_STATE_FAIL_CONNECT;
mbsStatus = e.message;
console.log("Error:"+e);
});
client.setTimeout (20);
}
//read data
Manager.prototype.readData = function(){
var self = this;
client.setID(2);
// try to read data
client.readCoils (0, 7, function(error,data){
if(!error){
self.checkEmergency();
}
});
}
//emergency
Manager.prototype.checkEmergency= function(){
}
exports.Manager=Manager;
client part of code is about a modbus application.
When I try to call "self.checkEmergency()" from readData, I have this error:
"self.checkEmergency() is not a function"
Why?
The method readData is called inside a method like this:
Manager.prototype.caller= function(){
var self = this;
self.readData();
}
I also have used self to pass the object to the callback...
Any idea?

Invalid Locator error

I tried to rewrite my tests in Page Object style but something goes wrong.
I use Class Tab and this is a part of my code:
var World = require('../support/world.js');
const isAllAjaxRequests = require('../scripts/util').isAllAjaxRequests;
const isElementLocatedAndVisible = require('../scripts/util').isElementLocatedAndVisible;
module.exports.Tab = class Tab {
constructor(data) {
this.name = "Base";
this.locators = {
'nextStepIsLocked': {xpath: '//md-tab-item[#aria-selected="true"]//div[#class="cc-status red"]'},
'isActiveTab': {xpath: '//md-tab-item[#aria-selected="true"]//span[text()="'+ data + '"]'}
}
}
waitForElement(bySelector) {
var driver = World.getDriver();
var self = this;
//var bySelector = self.locators[bySelector];
return driver.wait(isAllAjaxRequests(driver), waitTimeOut).then(() => {
//console.log(bySelector)
return driver.wait(isElementLocatedAndVisible(bySelector), waitTimeOut);
});
}
tabIsOpen(tabName) {
var driver = World.getDriver();
var self = this;
var bySelector = By.xpath('//md-tab-item[#aria-selected="true"]//span[text()="'+ tabName + '"]');
return self.waitForElement(bySelector);
}
}
Code in util:
exports.isElementLocatedAndVisible = function isElementLocatedAndVisible(driver, bySelector) {
return new Condition('element is located and visible', function(driver) {
console.log(bySelector)
return driver.findElements(bySelector).then((arr) => {
if (arr.length > 0) {
return arr[0].isDisplayed();
}
else {
return false;
}
});
});
};
I tried to use is in my test:
this.Then(/^Tab "([^"]*)" is open$/, function (tabName) {
this.createTab(tabName);
//var bySelector = tab.getLocator(isActiveTab);
return tab.tabIsOpen(tabName);
});
But I recieved an Invalid Locator error.
Via debug print I see thah I miss bySelector value when code go to exports.isElementLocatedAndVisible function. This is undefiened.
What I did wrong?
I suspect it is just missing of a parameter causing the issue.
In the following line:
return driver.wait(isElementLocatedAndVisible(bySelector), waitTimeOut);
add driver object as first argument and then bySelector, as follows:
return driver.wait(isElementLocatedAndVisible(driver, bySelector), waitTimeOut);
function is defined as follows:
function isElementLocatedAndVisible(driver, bySelector)
so, expecting driver object along with bySelector

Start object from setInterval?

I have the following reconnect method for Sockjs which almost is fully working:
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
clearInterval(connectRetry);
$('.connect-status')
.removeClass('disconnected')
.addClass('connected')
.text('Connected');
};
warbleSocket.onmessage = function(e) {
$('#warble-msg').text(e.data);
};
warbleSocket.onclose = function() {
clearInterval(connectRetry);
connectRetry = setInterval(connectToServer, 1000);
$('.connect-status')
.removeClass('connected')
.addClass('disconnected')
.text('Disconnected');
};
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
var connectRetry = setInterval(connectToServer, 1000);
})();
The error i am getting is when its trying to reconnect.
Error is:
SyntaxError: missing ] after element list
at this line:
connectRetry = setInterval(connectToServer, 1000);
Any ideas what im doing wrong here?
Your connectToServer variable is not a function, it's an object with a property send that is a function, so it doesn't make sense to say setInterval(connectToServer, 1000). Try this instead:
setInterval(connectToServer.send, 1000);
Why don't you simplify things a bit?
I would put connection stuff inside a specific function and call it from setInterval().
Something like this (use with care since I'm not testing this code, ok?):
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket;
function connect() {
warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
// ...
};
warbleSocket.onmessage = function(e) {
// ...
};
warbleSocket.onclose = function() {
// ...
}
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
// you probably will need to call the first connection
connectToServer();
// and than set connection retry
var connectRetry = setInterval(connectToServer.connect, 1000);
})();
I hope it helps you.
Regards,
Heleno

Functions are undefined

I am trying to create a data management application, but instead of a Windows-based solution or using WebSQL, i am using IndexedDB. I am pretty new to it but I believe I have covered the basis in this draft of code.
Anyway, my problem is, anytime I run the code, my openDB() function and the addeventListener() function both run and show on the console log at runtime but all other functions are said to be undefined when I try to run the code. What could the problem be?
In the HTML file, the jQuery script file is referenced.
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
var DB_STORE_NAME = 'visitors';
var db;
var current_view_pub_key;
//opens the IndexedDB database
function openDb() {
console.log("open Database......");
var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onsuccess = function (evt) {
db = this.result;
console.log("Database Opened");
};
req.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
req.onupgradeneeded = function (evt) {
console.log("Event fired when DB is needed to be upgraded");
var store = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
store.createIndex('name', 'name', { unique: false });
store.createIndex('date', 'date', { unique: false });
store.createIndex('whom_to_see', 'whom_to_see', { unique: false });
store.createIndex('arrival_time', 'arrival_time', { unique: false });
store.createIndex('reason', 'reason', { unique: false });
store.createIndex('departure_time', 'departure_time', { unique: false });
};
}
//used to create a transaction
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
//adds a Visitor to the IndexedDB
function addVisitor(name, date, to_see, arrival_time, reason, departure_time) {
console.log("Adding the following data to IndexedDB: ", arguments);
var obj = { name: name, date: date, whom_to_see: to_see, arrival_time: arrival_time, reason: reason, departure_time: departure_time };
if(typeof blob != undefined)
{
obj.blob = blob;
}
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req;
try
{
req = store.add(obj);
}
catch(e)
{
if(e.name == 'DataCloneError')
displayActionFailure("This engine does not know how to clone a Blob, use Firefox!");
throw(e);
}
req.onsuccess = function (evt) {
console.log("Insertion into DB was successful. You can heave a huge sigh of relief!");
displayActionSuccess();
};
req.onerror = function () {
console.error("Insertion into DB failed!");
displayActionFailure(this.error);
};
}
function displayActionSuccess() {
alert("Whatever the heck you were doing was successful. Congrats!");
}
function displayActionFailure() {
alert("Oh Oh! System Failure! System Failure!");
}
// listens for the submit button event
function addEventListeners() {
console.log("Event Listeners");
$('#addVisitor').click(function(evt) {
console.log("Add Visitors Submit button");
var name = document.getElementsByName("txtName").value;
var date = document.getElementsByName("txtDate").value;
var whom_to_see = document.getElementsByName("txtToSee").value;
var time_of_arrival = document.getElementsByName("txtArrivalTime").value;
var reason_for_visit = document.getElementsByName("txtReason").value;
var time_of_departure = document.getElementsByName("timeOfDep");
addVisitor(name, date, whom_to_see, time_of_arrival, reason_for_visit, time_of_departure);
});
}
//makes the database open at runtime
openDb();
addEventListeners();
})
();
syntax error - you need a closing round bracket at end.
i.e add
);
I think the problem is the fact that when your anonymous function is run the browser doesn't not know about the '#addVisitor' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
...
Instead of referencing the javascript code like before...
I removed all other functions from the javascript file leaving the openDB() function and placed them in the main html file. it worked automatically.

Categories

Resources