Codename one network manager waiting forever - networking

With the latest build of Codename One network code that used to work has suddenly broken.
This code, which uses NetworkManager's addToQueueAndWait() method is now blocking forever. Even if a timeout is set.
This was working before the last update to Codename One.
Here is a sample code snippit:
final int[] returnValue = new int[1];
ConnectionRequest r = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
returnValue[0] = 2;
}
};
r.setUrl(NetworkManager.getAutoDetectURL());
r.setPost(false);
r.setFailSilently(true);
r.setTimeout(10000);
NetworkManager.getInstance().addToQueueAndWait(r);
return returnValue[0];

Related

JavaFX Task updateValue throws IllegalStateException: Not on FX application thread

I have a simple application with a single JavaFX window. I'm sending in data to an Azure IoTHub inside a for loop. This for loop is in a JavaFX Task, and the for loop has a small delay (Thread.sleep(300)) so progress can be shown on the UI. I have 2 labels I want to update during the data transmission, always showing the latest sent in data. I have the following helper class for this:
public class DataHelper {
private StringProperty date = new SimpleStringProperty();
private StringProperty count = new SimpleStringProperty();
public DataHelper() {
}
public DataHelper(String date, String count) {
this.date.setValue(date);
this.count.setValue(count);
}
//getters and setters
}
And here is my sendErrorsToHub method inside my UI controller class:
private void sendErrorsToHub(List<TruckErrorForCloud> toCloud) {
DataHelper dataHelper = new DataHelper("", "");
Task task = new Task<DataHelper>() {
#Override
public DataHelper call() {
try {
int i = 0;
for (TruckErrorForCloud error : toCloud) {
Thread.sleep(300);
i++;
String strMessage = Utility.toPrettyJson(null, error);
if (strMessage != null) {
Message msg = new Message(strMessage);
msg.setMessageId(java.util.UUID.randomUUID().toString());
client.sendEventAsync(msg, null, null);
}
updateProgress(i, toCloud.size());
DataHelper dh = new DataHelper(error.getErrorTimeStamp().substring(0, error.getErrorTimeStamp().length() - 9),
String.valueOf(error.getCount()));
updateValue(dh);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void updateValue(DataHelper value) {
super.updateValue(value);
dataHelper.setDate(value.getDate());
dataHelper.setCount(value.getCount());
}
//succeeded method omitted
};
dateValue.textProperty().bind(dataHelper.dateProperty());
countValue.textProperty().bind(dataHelper.countProperty());
progressBar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
}
When I run the application, I constantly get IllegalStateException: Not on FX application threadexceptions, inside the updateValue method. As far as I understand the documentation, the whole point of the updateValue method, that it runs on the Application thread, and it can be used to pass a custom object, which can be used to update the UI.
What am I doing wrong then?
The bottom of the stacktrace with my classes is the following:
at eu.mantis.still_rca_simulator.gui.DataHelper.setDate(DataHelper.java:28)
at eu.mantis.still_rca_simulator.gui.GuiController$1.updateValue(GuiController.java:166)
at eu.mantis.still_rca_simulator.gui.GuiController$1.call(GuiController.java:155)
at eu.mantis.still_rca_simulator.gui.GuiController$1.call(GuiController.java:138)
(138 is the line Task task = new Task(), 155 updateValue(dh);, 166 dataHelper.setDate(value.getDate());)
updateValue does not automatically run on the application thread and it's not necessary to run it on the application thread since it takes care of updating the value property of Task on the application thread.
Your code in the overridden version updateValue executes logic on the background thread that needs to be run on the application thread though:
dataHelper.setDate(value.getDate());
dataHelper.setCount(value.getCount());
The bindings result in the text properties being updated from the background thread since the above code runs on the background thread.
In this case I recommend using a immutable DataHelper class and updating the ui using a listener to the value property:
Remove the updateValue override and the dataHelper local variable, initialize the gui with empty strings, if necessary, declare task as Task<DataHelper> task and do the following to update the gui:
task.valueProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
dateValue.setText(newValue.getDate());
countValue.setText(newValue.getCount());
}
});
You may also use Platform.runLater for those updates, since they don't happen frequently enough to result in issues that could be the result of using Platform.runLater too frequently.

ProcessBuilder Output hangs on readLine

I am trying to run some commands using ProcessBuilder and everything is working fine besides one small detail: in one case I only get the output when the task finishes running. I checked the program, and it is hanging on the first readLine(). I am running it in separate threads and I tried already both merging the input and error streams with "redirectErrorStream(true)" and having them separate with no changes in the mentioned behavior. I also tried to have a while loop that would only do the first readLine() after BufferedReader returning true for ready() but it didn't work (maybe not a very clever solution but I am trying everything to understand what is going on...)
The code works perfectly with some executables, giving output while it's running, but in some cases hangs on the first readline()... Someone has any idea what might cause that and how to solve it?
It is a little strange for me, given that when I execute the same command in the command prompt the output is shown while the program is running.
This question seems the same as the one I found in other threads but I couldn't find a solution for this in any of them.
Here is the code I am using, based on (http://thilosdevblog.wordpress.com/2011/11/21/proper-handling-of-the-processbuilder/):
List<String> command = new ArrayList<String>();
command.add(%COMMAND1)
command.add(%COMMAND2)
...
ProcessBuilderWrapper pbd = new ProcessBuilderWrapper(command);
ProcessBuilderWrapper:
public class ProcessBuilderWrapper {
public ProcessBuilderWrapper(File directory, List command) throws Exception {
ProcessBuilder pb = new ProcessBuilder(command);
if (directory != null) {
pb.directory(directory);
}
pb.redirectErrorStream(true);
Process process = pb.start();
StreamBoozer seInfo = new StreamBoozer(process.getInputStream());
seInfo.start();
}
public ProcessBuilderWrapper(List command) throws Exception {
this(null, command);
}
}
StreamBoozer:
public class StreamBoozer extends Thread {
private InputStream in;
StreamBoozer(InputStream in) {
this.in = in;
}
#Override
public void run() {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(in));
try {
String line = null;
while ((line = br.readLine()) != null) { <<<<<<<<<<<<< It hangs here #####
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thank you!
I think you misunderstand the building of the list command. The list can't be use for more than 1 command. That means, you can run one command only with ProcessBuilderWrapper.
Have as look at the Javadoc of the ProcessBuilder:
command - a string array containing the program and its arguments
E.g. for 'ls -al' you should use:
List command = new ArrayList();
command.add("ls");
command.add("-al");
If you are using the SteamBoozer-stuff Process,waitFor and SteamBoozer.join should be used (look at the blog article you mentioned above). Otherwise you could run into ugly timing issues! This can lead to the strange behavior you described above.
Regards
Thilo

Asynctask read xml parallely in viewpager get crashed in android

I use xml parser to read asynctask parallel (multiple thread) in viewpager.
Here my problem is while I swipe my viewpager fastly app get crashed.
Here is my code
private void doTheAutoRefresh(final int n) {
final ExecutorService es = Executors.newFixedThreadPool(7);
//final CountDownLatch latch = new CountDownLatch(n);
t=new Thread(){
#Override
public void run() {
this.setPriority(10);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
load =new LoadWebPageASYNC(n);
load.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else{
load=new LoadWebPageASYNC(n);
load.execute();}
}
};
t.setPriority(10);
es.execute(t);
}
Could you please help me what I am gets wrong.
I think the problem is with update current fragment.
I am new to android so please guide me for right direction.
I do not understand why you are creating a thread pool and then start single new Thread. At first sight it seems you do not want to call final ExecutorService es = Executors.newFixedThreadPool(7); every time you call doTheAutoRefresh
do you start a new Thread in LoadWebPageASYNC(n) as well ?
Maybe you can post the error message and a bit more code.
kind regards
Anton

JavaFX auto-scroll auto-update text

Newbie question about JavaFX that I haven't been able to answer, despite knowing it must be pretty simple to do and not finding any resources on it anywhere I've looked (tutorials, many of the Oracle online docs, articles, the well-known JavaFX bloggers, etc.)
I'm developing a command line (script) running application and I have successfully gotten output (via ProcessBuilder) from the script that I can display in an ongoing manner, as things happen on the command line. That is, I can do System.out.println(line); all day long, showing the output in the console, which simply returns output from an input stream returned by the 'myProcess' that's running, created like this:
BufferedReader bri = new BufferedReader(new InputStreamReader(myProcess.getInputStream()))
So I am able to see all the output coming back from the script.
I'd like to set-up a JavaFX TextArea or ScrollPane or, not sure what, to display this output text (there's a lot of it, like several thousand lines) as an ongoing 'progress' of what's taking place in the script, as it happens. I have a Scene, I have buttons and get input from this scene to start the script running, but now I'd like to show the result of clicking the button "RUN THIS SCRIPT", so to speak.
I assume I need to create a TextArea as described here or perhaps a TextBuilder would be useful to begin making it. Not sure.
I need a bit of help in how to setup the binding or auto-scroll/auto-update part of this.
Can someone provide me a place to start, to do this with JavaFX? I'd rather not use Swing.
(I'm using JavaFX 2.2, JDK 1.7u7, all the latest stuff, and yes, this is an FXML app--so doing it that way would be preferred.)
UPDATE: Sergey Grinev's answer was very helpful in the binding part. But here is some more detail on what I mean when I ask for "a bit of help in how to setup" -- basically, I need to return control to the main Scene to allow the user to Cancel the script, or to otherwise monitor what's going on. So I'd like to "spawn" the process that runs that script (that is, have some kind of 'free running process'), but still get the output from it. (I wasn't very clear on that in my initial question.)
The technique I'm using here (see below) is to do a waitFor on the process, but of course this means the dialog/Scene is 'hung' while the script executes. I'd like to gain control back, but how do I pass the 'p' (Process) to some other controller piece (or alternatively, simply kick off that other process passing in the parameters to start the script and have it start the script) that will then do the auto-update, via the binding Sergey Grinev mentions--without 'hanging' the Scene/window? Also: Can I then 'stop' this other process if the user requests it?
Here is my current code ('waits' while script--which takes 20-40 min to run!--completes; this is not what I want, I'd like control returned to the user):
public class MyController implements Initializable {
#FXML
private void handleRunScript(ActionEvent event) throws IOException {
ProcessBuilder pb = new ProcessBuilder("myscript.sh", "arg1", "arg2", ...);
Process p = pb.start();
try {
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
textAreaRight.setText(line);
}
bri.close();
p.waitFor();
}
catch (Exception err) {
err.printStackTrace();
}
}
#FXML
private void handleCancel(ActionEvent event) {
doSomethingDifferent();
}
}
To log strings you can use TextArea
To make it asynchronious you need to make a separate thread for output reader.
public class DoTextAreaLog extends Application {
TextArea log = new TextArea();
Process p;
#Override
public void start(Stage stage) {
try {
ProcessBuilder pb = new ProcessBuilder("ping", "stackoverflow.com", "-n", "100");
p = pb.start();
// this thread will read from process without blocking an application
new Thread(new Runnable() {
#Override
public void run() {
try {
//try-with-resources from jdk7, change it back if you use older jdk
try (BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = bri.readLine()) != null) {
log(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}).start();
stage.setScene(new Scene(new Group(log), 400, 300));
stage.show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public void stop() throws Exception {
super.stop();
// this called on fx app close, you may call it in user action handler
if (p!=null ) {
p.destroy();
}
}
private void log(final String st) {
// we can access fx objects only from fx thread
// so we need to wrap log access into Platform#runLater
Platform.runLater(new Runnable() {
#Override
public void run() {
log.setText(st + "\n" + log.getText());
}
});
}
public static void main(String[] args) {
launch();
}
}

How to close database in Cursorloader

I'm currently working on ListViews in Fragments. The Listviews are loaded by Cursorloader, but without ContentManager. So the code looks like this and it works:
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Log.d("SoapERP", "onCreateLoader");
CursorLoader loader = new CursorLoader(getActivity()) {
final DBHelper dbhelper1= new DBHelper(getActivity());
#Override
public Cursor loadInBackground() {
Cursor c = null;
dbhelper1.open();
c = dbhelper1.fetchAllMatnameswithID();
// dbhelper1.close();
return c;
}
};
return loader;
My problem is that I get an LogCat-Error-Message that the database wasn't closed. But if I use dbhelper.close(); I get the Error "Database is already closed" wich is also understandable because it is just before the return statement. After the return statement code is not reachable and if I declare DBHelper dbhelper1 final the program crashes without any information in logcat. So what is my fail???
Finally I found here the right statement as of Dianne Hackborn from android framework development: "A content provider is created when its hosting process is created, and remains around for as long as the process does, so there is no need to close the database -- it will get closed as part of the kernel cleaning up the process's resources when the process is killed. Dianne Hackborn Android framework engineer hack...#android.com " - so let's use Content Provider.

Resources