No errors in Eclipse but will not run on Blackberry Simulator. Error 104 illegalmonitorstateexception - blackberry-simulator

When running the App in the simulator i get the error msg App Error 104 illegalmonitorstateexception on startup.
There are no errors from within Eclipse and the Simulator works on other code so nothing wrong there i think.
Code:
package mypackage;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
class hello extends UiApplication {
hello() {
MainScreen SCREEN = new MainScreen();
SCREEN.setTitle("mygismo.com");
// CREATE STRING
String[] mymsgs = { "Cheese", "Pepperoni", "Black Olives" };
// AND INITIATE LOOP
for (int i = 0; i < 10; i++) {
// UPDATE SCREEN
SCREEN.add(new LabelField(mymsgs[i]));
pushScreen(SCREEN);
// WAIT 5 seconds
try {
wait(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
hello APP = new hello();
APP.enterEventDispatcher();
}
}

You are adding the same screen over and over again.
That's the problem.

Related

Codenameone BrowserComponent.setProperty giving NullPointerException

Until today, my code has been working great. However, I've just started getting NPE when using the Crisp CN1lib. It turns out that BrowserComponent.setProperty() is the culprit. Here is my stacktrace
java.lang.NullPointerException
at com.codename1.impl.javase.JavaSEPort.setBrowserProperty(JavaSEPort.java:11340)
at com.codename1.ui.BrowserComponent.setProperty(BrowserComponent.java:607)
Looks like the JavaSEPort.setBrowserProperty() is causing it. Github shows the code was edited 2 days ago so maybe something broke.
My code is pretty basic:
import static com.codename1.ui.CN.*;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.BrowserComponent;
import com.codename1.ui.Toolbar;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.layouts.BorderLayout;
/**
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
public class MyApplication {
private Form current;
private Resources theme;
public void init(Object context) {
// use two network threads instead of one
updateNetworkThreadCount(2);
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
Log.bindCrashProtection(true);
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if(err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
}
public void start() {
if(current != null){
current.show();
return;
}
BrowserComponent browser = new BrowserComponent();
browser.addWebEventListener(BrowserComponent.onLoad, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
}
});
browser.setProperty("UseWideViewPort", true);
browser.setProperty("LoadWithOverviewMode", true);
browser.setProperty("DatabaseEnabled", true);
browser.setProperty("BuiltInZoomControls", true);
browser.setProperty("DisplayZoomControls", false);
browser.setProperty("WebContentsDebuggingEnabled", true);
browser.setFireCallbacksOnEdt(true);
browser.setURL("https://www.instagram.com/brianabette/");
Form hi = new Form("Hi World", new BorderLayout());
hi.add(BorderLayout.CENTER, browser);
hi.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
}
Any pointers? Bug maybe?
We just made some performance improvements to BrowserComponent. Looks like we missed a spot here, so there is a regression. It is already fixed in Git and will be included in the next update next Friday.

Request thread interrupt not working on Ios

I create a new thread, and y need to interrupt, I use the thread.interrup(), but when I throw request thread interrupt is not working on ios, works fine on simulator or in Android device.
I Attach code to try it.
My temporal solution is use a Flag to break while, but I want to use the InterruptedException
package com.kandy.forms;
import com.codename1.io.Log;
import com.codename1.ui.Button;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.layouts.BoxLayout;
public class Interrup extends Form {
private Form previous;
private Thread thread = null;
public Interrup() {
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Button newThread = new Button ("Start Thread");
newThread.addActionListener((e) -> {
thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
Log.p("thread working");
} catch (InterruptedException ie) {
Dialog.show("Message", "Interruption received", "Ok", null);
break;
}
}
}
});
//thread start
thread.start();
});
Button interruptTreath = new Button ("Interrupt");
interruptTreath.addActionListener((e) -> {
Log.p("Interrupt Sended");
thread.interrupt();
});
add(newThread);
add(interruptTreath);
}
public void show() {
previous = Display.getInstance().getCurrent();
super.show();
}
public void goBack(){
previous.showBack();
}
}
This isn't supported on iOS. Neither is stop etc. as those are pretty hard to get working consistently across platforms. This is especially true for iOS and the thread implementation in the JavaScript port.

Java FX - can't close window in loop

I write short program in JavaFX which monitors folder for every 5 seconds . When it finds any PDF file then shows informations about number of finds files. And everything works fine, but when in folder is any files, then I will see window (and this is ok), but after this, when I will delete files (folder will be empty) then window is still showing (but is inactiv). Why this window doesn't close? Have you any idea?
Below is my code:
package testFolder;
import java.io.*;
import javafx.application.Application;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
public class App extends Application{
private static String searchPath;
private File[] childrenFiles;
#Override
public void init(){
setPath();
}
#Override
public void start(Stage primaryStage){
run();
}
public File[] findPDFFiles(){
System.out.println("Find file in: " + searchPath);
File directory = new File(searchPath);
File[] childrenFiles = directory.listFiles(
(dir, name) -> {
return name.toLowerCase().endsWith(".pdf");
}
);
System.out.println("Number files: " + childrenFiles.length);
return childrenFiles;
}
// search folder
public void run(){
while (true){
childrenFiles = findPDFFiles();
if ((childrenFiles.length > 0)){
String countFile = "Number files: " + childrenFiles.length;
showAndWait(AlertType.INFORMATION, "FILES FOUND", countFile);
}
// wait 5 seconds
try{
Thread.sleep(5000);
}
catch (InterruptedException iex){
iex.printStackTrace();
};
}
}
// shows window with information about number of found files
private static void showAndWait(
AlertType alertType,
String title,
String content) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(content);
alert.getDialogPane().setPrefWidth(800);
alert.showAndWait();
}
// set folder to search files
public void setPath(){
searchPath = "/Users/Marcin/Desktop/IN/";
}
public static void main(final String[] args){
launch();
}
}
I tried your code and it worked fine for me even after deleting all pdf files it will print Number files: 0 in the console and no alerts are showing.
however, i will suggest using an AnimationTimer instead of the while(true) loop
an animationTimer has a handle method which is an abstract method that you'll have to override when you create the AnimationTimer
the code inside handle will be executed every frame so it will work like your while(true) but better
but be careful ! you can't directly call showAndWait inside an AnimationTimer handle so you'll do it by calling Platform.runLater, and this won't stop the animation timer from executing its handle method
so you can stop the animationTimer whenever you have to show an alert, and start it back when the alert gets hidden (closed) mainly to prevent the timer from creating a lot of alerts if you do not close old ones
one last problem is that the javafx platform will automatically shutdown whenever there is no javafx context shown so you can stop that by setting ImplicitExit to false in your start method !
after applying all of the above explained stuff, your code will look like this
package testFolder;
import java.io.*;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
public class App extends Application{
private static String searchPath;
private static File[] childrenFiles;
static AnimationTimer timer;
static long then = 0;
#Override
public void init(){
setPath();
}
#Override
public void start(Stage primaryStage){
Platform.setImplicitExit(false);
run();
}
public static File[] findPDFFiles(){
System.out.println("Find file in: " + searchPath);
File directory = new File(searchPath);
File[] childrenFiles = directory.listFiles((dir, name) -> {
return name.toLowerCase().endsWith(".pdf");
});
System.out.println("Number files: " + childrenFiles.length);
return childrenFiles;
}
// search folder
public static void run(){
timer = new AnimationTimer() {
long sum = 0;
#Override
public void handle(long now) {
long dt = now - then;
sum+=dt;
if(sum/1000000 > 5000) {
childrenFiles = findPDFFiles();
if ((childrenFiles.length > 0)){
this.stop();
String countFile = "Number files: " + childrenFiles.length;
showAndWait(AlertType.INFORMATION, "FILES FOUND", countFile);
}
sum=0;
}
then = now;
}
};
timer.start();
}
// shows window with information about number of found files
private static void showAndWait(AlertType alertType, String title, String content) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(content);
alert.getDialogPane().setPrefWidth(800);
alert.setOnHidden(e->{
then = System.nanoTime();
timer.start();
});
Platform.runLater(alert::showAndWait);
}
// set folder to search files
public void setPath(){
searchPath = "/Users/Marcin/Desktop/IN/";
}
public static void main(final String[] args){
launch(args);
}
}
hope this solves you're problem

CN1 Library - No code fires in runOnUiThread

No code is firing in runOnUiThread in the native implementation. Codes before runOnUiThread does fire. I am sure I am not doing something right.
I created the CodenameOne Library like this
package com.uithread.test;
import com.codename1.system.NativeInterface;
public interface UIThreadNative extends NativeInterface {
public void runNativeCode();
}
package com.uithread.test;
import com.codename1.system.NativeLookup;
import com.codename1.ui.Dialog;
public class UIThreadManager {
private static UIThreadNative uithreadNative;
public UIThreadManager() {
if (uithreadNative == null) {
uithreadNative = (UIThreadNative) NativeLookup.create(UIThreadNative.class);
if (uithreadNative == null) {
Dialog.show("Null implementation", " UIThread is not implemented yet in this platform.", "Ok", null);
throw new RuntimeException("UIThread is not implemented yet in this platform.");
}
}
if (!uithreadNative.isSupported()) {
Dialog.show("Unsupported", " UIThread is not supported in this platform.", "Ok", null);
throw new RuntimeException("UIThread is not supported in this platform.");
}
}
public void runNativeCode() {
uithreadNative.runNativeCode();
}
}
Native implementation for android
package com.uithread.test;
import android.content.Context;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.codename1.impl.android.*;
import com.codename1.ui.Dialog;
public class UIThreadNativeImpl {
private static Context context() {
return com.codename1.impl.android.AndroidNativeUtil.getActivity().getApplicationContext();
}
private static Activity activity() {
return com.codename1.impl.android.AndroidNativeUtil.getActivity();
}
public void runNativeCode() {
final Activity convenientActivity = activity();//AndroidNativeUtil.getActivity();
final CodenameOneActivity codenameoneActivity = (CodenameOneActivity) AndroidNativeUtil.getActivity();
final android.app.Activity app = (Activity) AndroidNativeUtil.getActivity();
Dialog.show("Activity", convenientActivity + " convenientActivity", "Ok", null);
Dialog.show("Activity", codenameoneActivity + " codenameoneActivity", "Ok", null);
Dialog.show("Activity", app + " App", "Ok", null);
convenientActivity.runOnUiThread(new Runnable() {
public void run() {
Dialog.show("In run", "Run started", "Ok", null);
}
});
}
public boolean isSupported() {
return true;
}
}
In Statemachine I run this in code on a button click.
#Override
protected void onMain_ButtonAction(Component c, ActionEvent event) {
UIThreadManager uIThreadManager = new UIThreadManager();
uIThreadManager.runNativeCode();
}
As I said earlier. The codes before runOnUiThread work but the codes in runOnUiThread does not work. The dialogs in the runNativeCode in the native implementation were for checking the activity in different flavors which shows correctly that the different flavors are the same.
Thanks.
The native UI thread is totally different from our EDT so showing a Codename One dialog from that thread would be a huge EDT violation that can cause a serious crash!
Since our dialog blocks safely you would be effectively blocking the entire application and crashing it.
We use this line which is pretty much equivalent to what you wrote quite a bit in Codename One and in libraries e.g. here:
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() { ... });

Thucyides Test cases Queuing

Implemented A Thucydides(SERENITY) BDD Environment for automated testing of version 0.9.269. I have seen that the runner of test cases picks up the random test stories. Is there any way so that the stories can be queued?
The code for PortalTestSuit is as
public class PortalTestSuite extends ThucydidesJUnitStories {
private static final Logger LOGGER = LoggerFactory.getLogger(PortalTestSuite.class.getName());
/**
* Instantiates a new Portal test suite.
*/
public PortalTestSuite() {
/*Some Code to check the server is working or not*/
/* Do all stories */
findStoriesCalled("*.story");
}}
Here, the findStories will pick up the random stories from the directory and executes relative code... but please let me know the way to queue the Stories. Thanks.
Yes, we can maintain the order of story by overriding storyPaths() method of ThucydidesJUnitStories class.
#Override
public List<String> storyPaths() {
try {
File file = new File(System.getProperty("user.dir").concat("/src/test/resources/StoryContextTest.script"));
try (FileReader reader = new FileReader(file)) {
char[] buffer = new char[(int) file.length()];
reader.read(buffer);
String[] lines = new String(buffer).split("\n");
List<String> storiesList = new ArrayList<>(lines.length);
StoryFinder storyFinder = new StoryFinder();
for (String line : lines) {
if (!line.equals("") && !line.startsWith("#")) {
if (line.endsWith("*")) {
for (URL classpathRootUrl : allClasspathRoots()) {
storiesList.addAll(storyFinder.findPaths(classpathRootUrl, line.concat("*/*.story"), ""));
}
} else {
storiesList.add(line);
}
}
}
return storiesList;
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private List<URL> allClasspathRoots() {
try {
return Collections.list(getClassLoader().getResources("."));
} catch (IOException e) {
throw new IllegalArgumentException("Could not load the classpath roots when looking for story files",e);
}
}
The stories are being loaded from StoryContextTest.script as
################# Stories goes here #################
stories/authentication/authentication/authentication.story
stories/authentication/authentication/authentication1.story
(Or)
*/authentication/* (will get stories randomly)
This way you can serialize your stories as in Thucydides.

Resources