phonegap displaying text in native textbox - java

I'm making an android app which uses bluetooth using phonegap and I'm having issues handling code because it get's called every 100ms.
I want to try if the issue occurs because my phonegap javascript code is to long causing delays.
To try this I want to dispaly the received message using a native textbox.
Is this possible? and How would I do this?
Thanks
Martijn
PS: I've tried using Toast but since I want to change the displayed value every 100ms this doesn't work.
Code
upon receiving a message this is the order the code is processed
bytes = mmInStream.read(buffer);
s_message = new String(buffer, 0, bytes);
String[] strArray = s_message.split(",");
mHandleReceivedThread = new HandleReceivedThread(strArray);
mHandleReceivedThread.start();
In the HandleReceivedThread:
if(strArrayReceived[0].startsWith("Pressure"))
{
if(strArrayReceived[1].contains("Pressure"))
{
double Pressure = Double.parseDouble(strArrayReceived[1].replace("Pressure", ""));
double PressureResult = Pressure/10;
String PressureValue = String.valueOf(PressureResult);
webView.sendJavascript("PressureValue = " + Pressure + ";");
webView.sendJavascript("document.getElementById('Pressure').innerHTML = " + PressureValue + ";");
Log.e(TAG, "Message fail: " + strArrayReceived[1] );
}
else
{
double Pressure = Double.parseDouble(strArrayReceived[1]
double PressureResult = Pressure/10;
String PressureValue = String.valueOf(PressureResult);
webView.sendJavascript("PressureValue = " + Pressure + ";");
webView.sendJavascript("document.getElementById('Pressure').innerHTML = " + PressureValue + ";");
}
}
this is basically what happens.
And this happens every 100ms , and for some reason the displaying of the Value has lag and sometimes the received message (which should be "Pressure,1500" , or a different value) is Pressure,1500Pressure , causing errors (which I've managed to fix). but this still isn't optimal.
The message is send correctly and if I use a simple chat app they are received correctly.
if there is anything else I should supply , just ask ;-)

Related

VMWare java SDK: When doesn't an available PerfMetricID report Data?

I'm trying to use vmware sdk for java to collect the perfomance data of each entity (cluster/datastore/Host/VM) in the vmware environment.
The idea is to get the available PerfMetricIds for the target entity with queryAvailablePerfMetric, query those and report the details of the counter, the timestamp and the value.
However when I get the PerfMetricIds for an entity, not every detected (returned) PerfMetricId is reporting data. For example for each Datastore I get at least 4 ids which do not return data when queried, these IDs represent the counters associated with the average number of read and write operations, and for a cluster I'm missing the cpu usage, and so on ...
so I was wondering when does this happen? Shouldn't every metric returned by queryAvailablePerfMetric report data? what am I missing here?
Minimal code snippet:
// VMWare credentials
String vmwareUrl = args[0];
String vmwareUsername = args[1];
String vmwarePassword = args[2];
// connect to vCenter
ServiceInstance si = new ServiceInstance(new URL(vmwareUrl), vmwareUsername, vmwarePassword, true);
// get performance manager
PerformanceManager perfMgr = si.getPerformanceManager();
// define the time window (the last one hour)
Calendar calTo = Calendar.getInstance();
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(calTo.getTime());
calFrom.add(Calendar.HOUR, -1);
// get any datastore for testing purposes
Folder rootFolder = si.getRootFolder();
ManagedEntity[] datastores = new InventoryNavigator(rootFolder).searchManagedEntities("Datastore");
ManagedEntity me = datastores[1];
// query all available metrics for the entity
PerfMetricId[] availablePmis = perfMgr.queryAvailablePerfMetric(me, calFrom, calTo, perfMgr.getHistoricalInterval()[0].getSamplingPeriod());
// create PerfQuerySpec
PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(me.getMOR());
qSpec.setMetricId(availablePmis);
qSpec.setFormat("csv");
qSpec.setStartTime(calFrom);
qSpec.setEndTime(calTo);
// query perf
PerfEntityMetricBase[] perfValues = perfMgr.queryPerf(new PerfQuerySpec[]{qSpec});
// Printing
System.out.println("Found pmis (CounterIDs only): ");
for (PerfMetricId pmi : availablePmis){
System.out.print(pmi.getCounterId() + ", ");
}
System.out.print("\nPmis with values:");
int pmisCount=0;
for (PerfEntityMetricBase value : perfValues) {
PerfMetricSeriesCSV[] csvValues = ((PerfEntityMetricCSV) value).getValue();
pmisCount += csvValues.length;;
for (PerfMetricSeriesCSV csv : csvValues) {
System.out.println("Counter ID: " + csv.getId().getCounterId() + " ---- Metric instance: " + csv.getId().getInstance());
System.out.println("\tInfo: " + ((PerfEntityMetricCSV) value).getSampleInfoCSV());
System.out.println("\tValues: " + csv.getValue());
}
}
System.out.println("---------------");
System.out.println("Detected PMIs: " + availablePmis.length);
System.out.println("PMIs with values: " + pmisCount);
Any help (or discussions) would be appreciated

How to get and set a JComboBox?

What I have attached below is a copy/paste of my attempt to get and set a series of JComboBox's. hName and hAddress are dealing with a JTextField, so those are working fine, but for some reason I can get from my combo box's, but I can't set to them and including a call to initialiseDatabase() will cause the program to fail.
infoHolder is a resultset and dbstatement is a statement. The database is connecting fine, and the table inside of it is prepared and accessible, it's just the setting of the combobox's that's the issue.
Any help appreciated, and apologies if I'm missing something fundamental in the code below above.
public void initialiseDatabase()
{
try
{
infoHolder = dBStatement.executeQuery("SELECT * FROM House");
infoHolder.next();
hName = infoHolder.getString("Name");
hAddress = infoHolder.getString("Address");
numRooms = infoHolder.getInt("numRooms");
Type = infoHolder.getString("Type");
charge = infoHolder.getString("roomCharge");
Access = infoHolder.getString("dAccess");
Info = infoHolder.getString("oInfo");
houseText.setText(" " +hName);
addressText.setText(" " +hAddress);
roomNumber.setSelectedItem(" " +numRooms);
roomType.setSelectedItem(" " +Type);
chargeRoom.setSelectedItem(" " +charge);
access.setSelectedItem(" " +Access);
oInfo.setText(" " +Info);
current2 = 1;
infoHolder.close();
}
catch(SQLException e8) {JOptionPane.showMessageDialog(this, "Database failed to initialise!", "Message Dialog", JOptionPane.INFORMATION_MESSAGE);;}
}

how to log an integer value with log.d?

I am very new to Android and am trying some simple log to get a random background color. I have the code and it returns an integer between 1-256, or so I think. I need to log the value to check if it's OK, but I'm not sure how to log it with Android.. I've been using System.out.println("stuff") to log stuff in the past but I believe that's not how you're supposed to do it in Android.
I have my class:
public static int backgroundColorRandomize()
that returns
return randomRGB;
and I try to log it like this
Log.d(backgroundColorRandomize(), "value = " + randomRGB);
but I need to convert the returned value from backgroundColorRandomize to a String in order for it to log.
I tried java's .toString but I'm not sure I'm using it right.. Any help would be appreciated! Thanks!
Log.d("MYINT", "value: " + randomRGB);
private static final String TAG = YourClass.class.getSimpleName();
...
android.util.Log.d(TAG, String.format("value = %d. random color = %d", randomRGB, backgroundColorRandomize()));
More info:
http://developer.android.com/reference/android/util/Log.html
https://developer.android.com/tools/debugging/debugging-log.html
Logging libraries: https://android-arsenal.com/tag/57
I prefer String.valueOf(value).
Log.d(String.valueOf(backgroundColorRandomize()), "value = " + randomRGB);
Log.d(backgroundColorRandomize() + "" /* <-- all you need. */, "value = " + randomRGB);
I use
Log.d("MYINT", "value: " + randomRGB.toString());

download cover art from musicbrainz with java

I am struggling for a couple of hours now on how to link a discid to a musicbrainz mbid.
So, using dietmar-steiner / JMBDiscId
JMBDiscId discId = new JMBDiscId();
if (discId.init(PropertyFinder.getProperty("libdiscid.path")))
{
String musicBrainzDiscID = discId.getDiscId(PropertyFinder.getProperty("cdrom.path"));
}
or musicbrainzws2-java
Disc controller = new Disc();
String drive = PropertyFinder.getProperty("cdrom.path");
try {
DiscWs2 disc =controller.lookUp(drive);
log.info("DISC: " + disc.getDiscId() + " match: " + disc.getReleases().size() + " releases");
....
I can extract a discid for freedb or musicbrainz easily (more or less), but I have not found a way on calculating the id I that I need to download cover art via the CoverArtArchiveClient from last.fm.
CoverArtArchiveClient client = new DefaultCoverArtArchiveClient();
try
{
UUID mbid = UUID.fromString("mbid to locate release");
fm.last.musicbrainz.coverart.CoverArt coverArt = client.getByMbid(mbid);
Theoretically, I assume, I could you the data collected by musicbrainzws2-java to trigger a search, and then use the mbid from the result ... but that cannot be the best option to do.
I am happy about any push into the right direction...
Cheers,
Ed.
You don't calculate the MBID. The MBID is attached on every entity you retrieve from MusicBrainz.
When getting releases by DiscID you get a list. Each entry is a release and has an MBID, accessible with getId():
for (ReleaseWs2 rel : disc.getReleases()){
log.info("MBID: " + rel.getId() + ", String: " + rel.toString());
}
You then probably want to try the CoverArtArchive (CAA) for every release and take the first cover art you get.
Unfortunately I don't know of any API documentation for musicbrainzws2 on the web. I recommend running javadoc on all source files.

DJ Native Swing javascript command problems

Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.

Categories