I'm trying to run a simple midlet on Java ME SDK 3.0 integrated into Netbeans 7.1 on Windows 7 Ultimate (just a UI). It was running fine until yesterday but now its showing an error and i can't see the midlet in the emulator. I don't think its anything related to compatibility issues because the applications were running just fine the other day. Could someone help me rectify this glitch or whatever it is? (No error in program i guess)
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class Facebook extends MIDlet {
public void startApp() {
Form f = new Form("Facebook Login");
try {
Image g = Image.createImage("/Facebook 2.png");
ImageItem img = new ImageItem(null, g, Item.LAYOUT_CENTER, null, Item.PLAIN);
f.append(img);
} catch (IOException e) {
e.printStackTrace();
}
TextField tf = new TextField("Email or Phone", null, 300, TextField.ANY);
f.append(tf);
TextField tf1 = new TextField("Password", null, 300, TextField.ANY);
f.append(tf1);
ChoiceGroup cg = new ChoiceGroup(null, ChoiceGroup.MULTIPLE);
cg.append("Remember Me",null);
f.append(cg);
StringItem str = new StringItem(null, "Forgot Password?", StringItem.HYPERLINK);
f.append(str);
try {
Image g2 = Image.createImage("/Fb Login 2.png");
ImageItem img2 = new ImageItem(null, null, Item.LAYOUT_CENTER, null, Item.BUTTON);
f.append(img2);
} catch (IOException e2) {
e2.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Message in output:
Starting emulator in execution mode
* Error *
Failed to connect to device 6!
Reason:
Failed to initialize connection with emulator 6! (possible runtime incompatibility)
F:\NetBeansProjects\MobileApplication2\nbproject\build-impl.xml:782: Execution failed with error code 1.
BUILD FAILED (total time: 12 seconds)
Related
I am trying to select "OK" button against my browser certificate pop-up using robot class. The same piece of code works well on windows but failing on ubuntu.
Code:
public void load() {
setUrl();
Thread threadNavigation = new Thread() {
#Override
public void run() {
driver.navigate().to(url);
}
};
Thread threadCertificateHandler = new Thread() {
#Override
public void run() {
try {
Thread.sleep(3000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(2000);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Start the threads.
threadNavigation.start();
threadCertificateHandler.start();
// Wait for them both to finish
try {
threadNavigation.join();
threadCertificateHandler.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Code Explanation:
As soon as url is navigated using selenium, a certificate pop-up is displayed before page is loaded.
The approach I have used here - 1 thread used here to get application url and another thread is used to handle the pop-up.
Attaching screenshot of the pop-up.
Chromedriver Code:
public void getStandaloneHubNodeServerDriver(String browserType,String platformType, String url) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
logger.log(Level.INFO, () -> "Setting browser address #: " + url);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
options.setAcceptInsecureCerts(true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
//threadLocalDriver.set(new RemoteWebDriver(new URL(url),options));
driver = new RemoteWebDriver(new URL(url),options);
driver.manage().window().maximize();
}
Chrome Image Used:
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:4.8.0-20230123
I am trying to connect my Desktop to the PHILIPS Hue light server using java.
When the code runs, it will flow into the Controller.java. When that happens, the FindBridges method in Controller.java runs. This is where the error occurs. In debugging, it displays a NullPointerException in thread "AWT-Event-Queue-0".
I presume that the server/lightbulb cannot be found at all, even though it is turned on and my android application can connect to it.
The error is stated below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.philips.lighting.gui.DesktopView$1.actionPerformed(DesktopView.java:72)
Controller.java
package com.philips.lighting;
import java.util.List;
import java.util.Random;
import javax.swing.JDialog;
import com.philips.lighting.hue.sdk.upnp.*;
import com.philips.lighting.data.HueProperties;
import com.philips.lighting.gui.AccessPointList;
import com.philips.lighting.gui.DesktopView;
import com.philips.lighting.gui.LightColoursFrame;
import com.philips.lighting.gui.PushLinkFrame;
import com.philips.lighting.hue.sdk.PHAccessPoint;
import com.philips.lighting.hue.sdk.PHBridgeSearchManager;
import com.philips.lighting.hue.sdk.PHHueSDK;
import com.philips.lighting.hue.sdk.PHMessageType;
import com.philips.lighting.hue.sdk.PHSDKListener;
import com.philips.lighting.model.PHBridge;
import com.philips.lighting.model.PHBridgeResourcesCache;
import com.philips.lighting.model.PHHueError;
import com.philips.lighting.model.PHHueParsingError;
import com.philips.lighting.model.PHLight;
import com.philips.lighting.model.PHLightState;
public class Controller {
private PHHueSDK phHueSDK;
private DesktopView desktopView;
private PushLinkFrame pushLinkDialog;
private LightColoursFrame lightColoursFrame;
private static final int MAX_HUE=65535;
private Controller instance;
public Controller(DesktopView view) {
this.desktopView = view;
this.phHueSDK = PHHueSDK.getInstance(); // or phHueSDK = PHHueSDK.getInstance();
this.instance = this;
}
public void findBridges() {
//To uniquely identify your app in the bridge whitelist we recommend you set your app name, and the device
phHueSDK.setAppName("SmartShowroomApp"); // e.g. phHueSDK.setAppName("QuickStartApp");
phHueSDK.setDeviceName("SmartDevice"); // e.g. If you are programming for Android: phHueSDK.setDeviceName(android.os.Build.MODEL);
phHueSDK = PHHueSDK.getInstance();
PHBridgeSearchManager sm = (PHBridgeSearchManager) phHueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
sm.search(true, true);
//This starts a UPNP/Portal Search and takes around 10 seconds.
//The PHSDKListener (onAccessPointsFound) will be notified with the bridges found.
}
private PHSDKListener listener = new PHSDKListener() {
#Override
public void onAccessPointsFound(List<PHAccessPoint> accessPointsList) {
// Handle your bridge search results here.
//Typically if multiple results are returned you will want to display them in a list
// and let the user select their bridge.
//If one is found you may opt to connect automatically to that bridge.
phHueSDK = PHHueSDK.getInstance();
desktopView.getFindingBridgeProgressBar().setVisible(false);
if (accessPointsList != null && accessPointsList.size() > 0)
{
AccessPointList accessPointList = new AccessPointList(accessPointsList, instance);
accessPointList.setVisible(true);
accessPointList.setLocationRelativeTo(null); // Centre the AccessPointList Frame
phHueSDK.getAccessPointsFound().clear(); // Clear all connected access points
phHueSDK.getAccessPointsFound().addAll(accessPointsList); // Adds multiple results to the list
}
else
{
PHBridgeSearchManager sm = (PHBridgeSearchManager) phHueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
sm.search(false, false, true);
}
}
#Override
public void onAuthenticationRequired(PHAccessPoint accessPoint) {
// Start the Pushlink Authentication.
phHueSDK = PHHueSDK.getInstance();
desktopView.getFindingBridgeProgressBar().setVisible(false);
phHueSDK.startPushlinkAuthentication(accessPoint);
// Arriving here indicates that Pushlinking is required (to prove the User has physical access to the bridge).
//Typically here you will display a pushlink image (with a timer) indicating to to the user they need to push the button on their bridge within 30 seconds.
pushLinkDialog = new PushLinkFrame(instance);
pushLinkDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pushLinkDialog.setModal(true);
pushLinkDialog.setLocationRelativeTo(null); // Center the dialog.
pushLinkDialog.setVisible(true);
}
#Override
public void onBridgeConnected(PHBridge bridge) {
phHueSDK = PHHueSDK.getInstance();
phHueSDK.setSelectedBridge(bridge);
phHueSDK.enableHeartbeat(bridge, PHHueSDK.HB_INTERVAL);
// Here it is recommended to set your connected bridge in your sdk object (as above) and start the heartbeat.
// At this point you are connected to a bridge so you should pass control to your main program/activity.
// Also it is recommended you store the connected IP Address/ Username in your app here.
//This will allow easy automatic connection on subsequent use.
// Remember to disable the heartbeat when exiting your app
//phHueSDK.disableAllHeartbeat();
//If you are only interested in a particular resource (e.g. Lights), you can enable the multi resource heartbeat as follows:
//PHHeartbeatManager heartbeatManager = PHHeartbeatManager.getInstance();
//heartbeatManager.enableLightsHeartbeat(bridge, PHHueSDK.HB_INTERVAL);
// To stop the heartbeat you can use either of the below
//heartbeatManager.disableLightsHeartbeat(bridge);
//heartbeatManager.disableAllHeartbeats(bridge);
desktopView.getFindingBridgeProgressBar().setVisible(false);
String username = HueProperties.getUsername();
String lastIpAddress = bridge.getResourceCache().getBridgeConfiguration().getIpAddress();
System.out.println("On connected: IP " + lastIpAddress);
HueProperties.storeUsername(username);
HueProperties.storeLastIPAddress(lastIpAddress);
HueProperties.saveProperties();
// Update the GUI.
desktopView.getLastConnectedIP().setText(lastIpAddress);
desktopView.getLastUserName().setText(username);
// Close the PushLink dialog (if it is showing).
if (pushLinkDialog!=null && pushLinkDialog.isShowing()) {
pushLinkDialog.setVisible(false);
}
// Enable the Buttons/Controls to change the hue bulbs.s
desktopView.getRandomLightsButton().setEnabled(true);
desktopView.getSetLightsButton().setEnabled(true);
}
#Override
public void onCacheUpdated(List cacheNotificationsList, PHBridge bridge) {
// Here you receive notifications that the BridgeResource Cache was updated. Use the PHMessageType to
// check which cache was updated, e.g.
if (cacheNotificationsList.contains(PHMessageType.LIGHTS_CACHE_UPDATED)) {
System.out.println("Lights Cache Updated ");
}
}
#Override
public void onConnectionLost(PHAccessPoint accessPoint) {
// Here you would handle the loss of connection to your bridge.
phHueSDK = PHHueSDK.getInstance();
if (accessPoint == null)
{
System.out.println("Please reconnect to your bridge.");
}
}
#Override
public void onConnectionResumed(PHBridge bridge) {
PHHueSDK phHueSDK = PHHueSDK.getInstance();
for (int i = 0; i < phHueSDK.getDisconnectedAccessPoint().size(); i++)
{
if (phHueSDK.getDisconnectedAccessPoint().get(i).getIpAddress()
.equals(bridge.getResourceCache().getBridgeConfiguration().getIpAddress())) {
phHueSDK.getDisconnectedAccessPoint().remove(i);
}
}
}
#Override
public void onError(int code, final String message) {
// Here you can handle events such as Bridge Not Responding, Authentication Failed and Bridge Not Found.
if (code == PHHueError.BRIDGE_NOT_RESPONDING) {
desktopView.getFindingBridgeProgressBar().setVisible(false);
desktopView.getFindBridgesButton().setEnabled(true);
desktopView.getConnectToLastBridgeButton().setEnabled(true);
desktopView.showDialog(message);
}
else if (code == PHMessageType.PUSHLINK_BUTTON_NOT_PRESSED) {
pushLinkDialog.incrementProgress();
}
else if (code == PHMessageType.PUSHLINK_AUTHENTICATION_FAILED) {
if (pushLinkDialog.isShowing()) {
pushLinkDialog.setVisible(false);
desktopView.showDialog(message);
}
else {
desktopView.showDialog(message);
}
desktopView.getFindBridgesButton().setEnabled(true);
}
else if (code == PHMessageType.BRIDGE_NOT_FOUND) {
desktopView.getFindingBridgeProgressBar().setVisible(false);
desktopView.getFindBridgesButton().setEnabled(true);
desktopView.showDialog(message);
}
}
#Override
public void onParsingErrors(List<PHHueParsingError> parsingErrorsList) {
// Any JSON parsing errors are returned here.
//Typically your program should never return these.
for (PHHueParsingError parsingError: parsingErrorsList) {
System.out.println("ParsingError : " + parsingError.getMessage());
}
}
};
public PHSDKListener getListener() {
return listener;
}
public void setListener(PHSDKListener listener) {
this.listener = listener;
}
public void randomLights() {
PHBridge bridge = phHueSDK.getSelectedBridge();
PHBridgeResourcesCache cache = bridge.getResourceCache();
// And now you can get any resource you want, for example:
List<PHLight> allLights = cache.getAllLights();
Random rand = new Random();
for (PHLight light : allLights) {
PHLightState lightState = new PHLightState();
lightState.setHue(rand.nextInt(MAX_HUE));
bridge.updateLightState(light, lightState); // If no bridge response is required then use this simpler form.
}
}
public void showControlLightsWindow() {
if (lightColoursFrame == null) {
lightColoursFrame = new LightColoursFrame();
}
lightColoursFrame.setLocationRelativeTo(null); // Centre window
lightColoursFrame.setVisible(true);
}
/**
* Connect to the last known access point.
* This method is triggered by the Connect to Bridge button but it can equally be used to automatically connect to a bridge.
*
*/
public boolean connectToLastKnownAccessPoint() {
String username = HueProperties.getUsername();
String lastIpAddress = HueProperties.getLastConnectedIP();
if (username==null || lastIpAddress == null) {
desktopView.showDialog("Missing Last Username or Last IP. Last known connection not found.");
return false;
}
//Obviously, every time a user opens up their Android hue app or application you don't want them to have to select their bridge, authenticate pushlink everytime.
//The recommended way to overcome this issue is to store the connected IP Address/Username (using your preferred method storage) and if set try to connect automatically.
PHAccessPoint accessPoint = new PHAccessPoint();
accessPoint.setIpAddress(lastIpAddress);
accessPoint.setUsername(username);
phHueSDK.connect(accessPoint);
return true;
//Note that the .connect method returns control to your PHSDKListener, so when connected the onBridgeConnected will be called again, and if your users Bridge IP has changed for example, onError will be called and can be handled programatically.
}
public void enableFindBridgesButton() {
desktopView.getFindBridgesButton().setEnabled(true);
}
public void showProgressBar() {
desktopView.getFindingBridgeProgressBar().setVisible(true);
}
}
DesktopView.java
package com.philips.lighting.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import layout.TableLayout;
import com.philips.lighting.Controller;
import com.philips.lighting.data.HueProperties;
/**
* DesktopView.java
*
* The main GUI showing last connected IP/Username and buttons for Finding Bridges and Changing the Hue Lights, once connected to a bridge.
*
*/
public class DesktopView extends JFrame {
private static final long serialVersionUID = -7469471678945429320L;
private Controller controller;
private JButton setLightsButton;
private JButton randomLightsButton;
private JButton findBridgesButton;
private JButton connectToLastBridgeButton;
private JProgressBar findingBridgeProgressBar;
private JTextField lastConnectedIP;
private JTextField lastUserName;
public DesktopView(){
setTitle("Hue Desktop");
JPanel mainPanel = new JPanel();
// TODO - Move to another class
JPanel controls = new JPanel();
controls.setLayout(new GridLayout(2,3));
findingBridgeProgressBar = new JProgressBar();
findingBridgeProgressBar.setBorderPainted(false);
findingBridgeProgressBar.setIndeterminate(true);
findingBridgeProgressBar.setVisible(false);
//Set up components preferred size
String lastUsername = HueProperties.getUsername();
String lastConnectedIPStr = HueProperties.getLastConnectedIP();
JLabel labelLastConIP = new JLabel("Last Connected IP:");
lastConnectedIP = new JTextField(lastConnectedIPStr);
lastConnectedIP.setEditable(false);
JLabel labelLastUsername = new JLabel("Last UserName:");
lastUserName = new JTextField(lastUsername);
lastUserName.setEditable(false);
findBridgesButton = new JButton("Find New Bridges");
findBridgesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
findBridgesButton.setEnabled(false);
connectToLastBridgeButton.setEnabled(false);
controller.findBridges();
findingBridgeProgressBar.setBorderPainted(true);
findingBridgeProgressBar.setVisible(true);
}
});
connectToLastBridgeButton = new JButton("Auto Connect");
connectToLastBridgeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (controller.connectToLastKnownAccessPoint()) {
connectToLastBridgeButton.setEnabled(false);
findBridgesButton.setEnabled(false);
findingBridgeProgressBar.setBorderPainted(true);
findingBridgeProgressBar.setVisible(true);
}
}
});
setLightsButton = new JButton("Change Light Colours");
setLightsButton.setEnabled(false);
setLightsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
controller.showControlLightsWindow();
}
});
randomLightsButton = new JButton("Randomize Lights");
randomLightsButton.setEnabled(false);
randomLightsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
controller.randomLights();
}
});
double border = 10;
double size[][] =
{{border, 160, 20, 300, 20, 160}, // Columns
{border, 26, 10, 26, 26, 26,6,26}}; // Rows
mainPanel.setLayout (new TableLayout(size));
mainPanel.add(labelLastConIP, " 1, 1");
mainPanel.add(lastConnectedIP, " 3, 1");
mainPanel.add(labelLastUsername, " 1, 3");
mainPanel.add(lastUserName, " 3, 3");
mainPanel.add(findingBridgeProgressBar, " 3, 5");
mainPanel.add(connectToLastBridgeButton, " 5, 1");
mainPanel.add(findBridgesButton, " 5, 3");
mainPanel.add(randomLightsButton, " 5, 5");
mainPanel.add(setLightsButton, " 5, 7");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(700,270));
getContentPane().add(new JLabel(" An example Java/Swing Desktop Application to control your Hue Lights."), BorderLayout.NORTH);
getContentPane().add(mainPanel, BorderLayout.CENTER);
//4. Size the frame.
pack();
setLocationRelativeTo(null); // Centre the window.
setVisible(true);
}
public void setController(Controller controller) {
this.controller = controller;
}
public JButton getSetLightsButton() {
return setLightsButton;
}
public JButton getRandomLightsButton() {
return randomLightsButton;
}
public JButton getFindBridgesButton() {
return findBridgesButton;
}
public JButton getConnectToLastBridgeButton() {
return connectToLastBridgeButton;
}
public void showDialog(String message) {
JOptionPane.showMessageDialog(this, message);
}
public JProgressBar getFindingBridgeProgressBar() {
return findingBridgeProgressBar;
}
public JTextField getLastConnectedIP() {
return lastConnectedIP;
}
public JTextField getLastUserName() {
return lastUserName;
}
}
HueDesktop.java
package com.philips.lighting;
import com.philips.lighting.data.HueProperties;
import com.philips.lighting.gui.DesktopView;
import com.philips.lighting.hue.sdk.PHHueSDK;
/**
* HueDesktop.java
* An example Java/Swing Desktop application illustrating how to connect to a bridge and change your Hue lights
* using a Java Desktop Application.
*
* For more information on programming for Hue see:
* http://developers.meethue.com
*
*/
class HueDesktop {
public static void main(String args[]) {
new HueDesktop();
}
public HueDesktop() {
PHHueSDK phHueSDK = PHHueSDK.create();
// Load in HueProperties, if first time use a properties file is created.
HueProperties.loadProperties();
// Set Up the View (A JFrame, MenuBar and Console).
DesktopView desktopView = new DesktopView();
// Bind the Model and View
Controller controller = new Controller(desktopView);
desktopView.setController(controller);
// Register the PHSDKListener to receive callbacks from the bridge.
phHueSDK.getNotificationManager().registerSDKListener(controller.getListener());
}
}
Did you ever solve this? In future it is probably best to post hue Java SDK issues on the GitHub site. https://github.com/PhilipsHue/PhilipsHueSDK-Java-MultiPlatform-Android/issues
I would have seen this sooner on here (I wrote this code btw so am possibly the culprit).
I do remember seeing a similar issue before, am pretty sure it was related to Macs and the JDK Compiler level used (I possibly used an incompatible Swing component on Mac and JDK 1.6). Can you let me know your OS and JDK Compiler level and I will check this further?
b1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement = connect.createStatement();
preparedStatement = connect
.prepareStatement("select * from mark where clsnum = " + txt1.getText() + "");
rs = preparedStatement.executeQuery();
if (rs.next()) {
delete();
} else {
msg.setText("Student Not Found...!");
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DeleteMark.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
This is my code to display a message if the query not worked(I mean if no row is returned to ResultSet rs). msg is an object of Text and its declaration and other details are -
Text msg = new Text();
msg.setFont(Font.font("Calibri", FontWeight.THIN, 18));
msg.setFill(Color.RED);
I want to make the Text disappear after sometime, like 3 or 4 seconds. Is it possible to do it in JavaFX (with the help of timer or something else you know) ? If yes, how ?
Use Timelines and/or Transitions.
This answer is for a previous iteration of the question.
Sample solution code
import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class BlinkingAndFading extends Application {
#Override
public void start(Stage stage) {
Label label = new Label("Blinking");
label.setStyle("-fx-text-fill: red; -fx-padding: 10px;");
Timeline blinker = createBlinker(label);
blinker.setOnFinished(event -> label.setText("Fading"));
FadeTransition fader = createFader(label);
SequentialTransition blinkThenFade = new SequentialTransition(
label,
blinker,
fader
);
stage.setScene(new Scene(new StackPane(label), 100, 50));
stage.show();
blinkThenFade.play();
}
private Timeline createBlinker(Node node) {
Timeline blink = new Timeline(
new KeyFrame(
Duration.seconds(0),
new KeyValue(
node.opacityProperty(),
1,
Interpolator.DISCRETE
)
),
new KeyFrame(
Duration.seconds(0.5),
new KeyValue(
node.opacityProperty(),
0,
Interpolator.DISCRETE
)
),
new KeyFrame(
Duration.seconds(1),
new KeyValue(
node.opacityProperty(),
1,
Interpolator.DISCRETE
)
)
);
blink.setCycleCount(3);
return blink;
}
private FadeTransition createFader(Node node) {
FadeTransition fade = new FadeTransition(Duration.seconds(2), node);
fade.setFromValue(1);
fade.setToValue(0);
return fade;
}
public static void main(String[] args) {
launch(args);
}
}
Answers to additional questions
lambda expression not expected here lambda expressions are not supported in -source 1.7 (use -source 8 or higher to enable lambda expressions)
You should use Java 8 and not set -source 1.7. If you wish to stick with Java 7 (which I don't advise for JavaFX work), you can replace the Lambda:
blinker.setOnFinished(event -> label.setText("Fading"));
with:
blinker.setOnFinished(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
label.setText("Fading");
}
});
actual and formal argument lists differ in length
Again, you should use Java 8. But if you wish to use Java 7, replace:
stage.setScene(new Scene(new StackPane(label), 100, 50));
with:
StackPane layout = new StackPane();
layout.getChildren().add(label);
stage.setScene(new Scene(layout, 100, 50));
Further recommendations
Good call on not having the text both blink and fade. Blinking text makes for pretty distracting UI, but just fading is fine.
I don't think I'd recommend fading an error message, at least until the user clicks on it or something like that. What if the user didn't see the error message before it faded away?
i am trying to insert Data in my DataBase using this Code but i'am getting an exception :
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
public class MyMidlet extends MIDlet implements Runnable {
Form f;
TextField t1 ;
Label label1 ;
Button b1;
TextField tfNom ;
TextField tfPrenom ;
//Connexion
HttpConnection hc;
DataInputStream dis;
String url ;
StringBuffer sb ;
int ch;
public MyMidlet() {
Display.init(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
f = new Form("Test");
tfNom = new TextField("nom : ");
tfPrenom = new TextField("prenom :");
b1=new Button("ok");
f.addComponent(tfNom); // append
f.addComponent(tfPrenom);
f.addComponent(b1);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("gooooo");
url= "http://localhost/J2ME/ajout.php";
sb = new StringBuffer();
//****************************
try {
hc = (HttpConnection) Connector.open(url+"?nom="+tfNom.getText()+"&prenom="+tfPrenom.getText());
dis = new DataInputStream(hc.openDataInputStream());
while ((ch = dis.read()) != -1) {
sb.append((char)ch);
}
// trim tna77i les espaces
if ("successfully added".equalsIgnoreCase(sb.toString().trim())) {
System.out.println("succes (added)");
}else{
System.out.println("Error While Adding Data");
}
} catch (IOException ex) {
ex.printStackTrace();
}
//***********************
System.out.println("I am Ouuuut");
}
});
f.show();
}
public void run() {
}
}
--> It does not work and I'am getting this exception :
i'am using NOKIA DevEnv for the first time. It used to work when I use it on Normal Netbeans J2ME.
Can any one help ?
gooooo
javax.microedition.io.ConnectionNotFoundException: error 0 in socket::open
- com.sun.midp.io.j2me.socket.Protocol.open0(), bci=0
- com.sun.midp.io.j2me.socket.Protocol.connect(), bci=143
- com.sun.midp.io.j2me.socket.Protocol.open(), bci=122
- com.sun.midp.io.j2me.socket.Protocol.openPrim(), bci=4
- com.sun.midp.io.j2me.http.Protocol.createConnection(), bci=13
- com.sun.midp.io.j2me.http.Protocol.connect(), bci=138
- com.sun.midp.io.j2me.http.Protocol.streamConnect(), bci=53
- com.sun.midp.io.j2me.http.Protocol.startRequest(), bci=7
- com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=33
- com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=3
- com.sun.midp.io.j2me.http.Protocol.openInputStream(), bci=6
- com.sun.midp.io.ConnectionBaseAdapter.openDataInputStream(), bci=5
- esprit.MyMidlet$1.actionPerformed(MyMidlet.java:89)
- com.sun.lwuit.util.EventDispatcher.fireActionSync(EventDispatcher.java:312)
- com.sun.lwuit.util.EventDispatcher.fireActionEvent(EventDispatcher.java:257)
- com.sun.lwuit.Button.fireActionEvent(Button.java:369)
- com.sun.lwuit.Button.released(Button.java:400)
- com.sun.lwuit.Button.pointerReleased(Button.java:476)
- com.sun.lwuit.Form.pointerReleased(Form.java:2059)
- com.sun.lwuit.Component.pointerReleased(Component.java:2065)
- com.sun.lwuit.Display.handleEvent(Display.java:1643)
- com.sun.lwuit.Display.edtLoopImpl(Display.java:894)
- com.sun.lwuit.Display.mainEDTLoop(Display.java:839)
- com.sun.lwuit.RunnableWrapper.run(RunnableWrapper.java:119)
- java.lang.Thread.run(), bci=5
I am Ouuuut
Either your application cannot connect to the internet or if it can, fails to connect to your web service using the link provided. Try entering the URL for your request in your web browser and see if it is reachable. If you are connecting to your web service through a specific port (eg. http://mylink.com:8085/my-web-service/), make sure that the specific port is not blocked.
Chris Mwai is right - the code provided tries to work with server at "http://localhost/J2ME/ajout.php" and obviously it doesn't exists. Probably the Netbeans project included server side code as well, which was deployed at localhost (user PC) and J2ME client connected to it from emulator.
You need to start server part somehow (it's specific to your project). In a real environment (not emulator) you will need to deploy the server part somewhere in internet and connect to it from app running on phone. So you will need to change url to that server. 'localhost' means a local server (your PC).
i am programming a mobile application in j2me in which i need to send an image from one mobile to another via sms.
the problem is being encountered at the receiving end.the image is not being decoded properly.it is throwing ioexception....i m posting the code here..plz help me.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.io.IOException;
import javax.microedition.lcdui.game.*;
import java.lang.*;
import java.io.*;
public class receive_mms extends MIDlet implements CommandListener
{
Display disp;
//TextBox txtbox;
MessageConnection msgConn;
Message msg;
Form frm=null;
byte[] msgrev;
byte[] data;
//String msgrev;
Image im=null;
Image im1=null;
ImageItem img=null;
int i,j;
ByteArrayInputStream bais = null;
Command cmd_exit;
public receive_mms(){
disp=Display.getDisplay(this);
frm=new Form("photo dikho");
i=frm.getWidth();
j=frm.getHeight();
cmd_exit=new Command("exit",Command.EXIT,1);
frm.addCommand(cmd_exit);
frm.setCommandListener(this);
disp.setCurrent(frm);
Thread t1 = new Thread()
{
public void run()
{recieve();}
};
t1.start();
//txtbox=new TextBox("Recieve Text","",100,TextField.ANY);
}
public void commandAction(Command c,Displayable d)
{
if(c==cmd_exit)
{
notifyDestroyed();
}
}
public void startApp(){/*
disp.setCurrent(frm);
Thread t1 = new Thread()
{
public void run()
{recieve();}
};
t1.start();
*/
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){}
public void recieve(){
//while(true)
//{
String mSenderAddress="";
try{
msgConn = (MessageConnection) Connector.open("sms://:1234");
System.out.println("11");
msg = msgConn.receive();// start listening and stuck here until a msg is received
System.out.println("12");
mSenderAddress = msg.getAddress();// Get info from message, from where da msg is beign sent
System.out.println("3");
System.out.println("add"+ mSenderAddress);
System.out.println("msg aya:" + msg);
msgConn.close();
}catch(Exception e){System.out.println(e);}
if (msg instanceof BinaryMessage) {
//try{
msgrev = ((BinaryMessage)msg).getPayloadData();
data=msgrev.toByteArray();
String val= new String(data);
System.out.println("yahoo");
System.out.println("yahoo1");
System.out.println(val);
create(data);
}
}
public void create(byte[] bs)
{
try
{
String str=bs.toString();
/*
StringBuffer d=new StringBuffer();
bais=new ByteArrayInputStream(bs);
DataInputStream ds=new DataInputStream(bais);
int len=bs.length;
System.out.println("len="+len);
if(len!=0)
{
int ch=0;
while((ch=ds.read())!=-1)
{
d.append((char)ch);
}
}
System.out.println(d);
str=d.toString();
*/
//str=bs.toString();
InputStream is= this.getClass().getResourceAsStream(str);
System.out.println("string is"+str);
im = (Image)Image.createImage(is);
System.out.println("line");
im1 = (Image)Image.createImage(im, 0, 0, i, j, Sprite.TRANS_NONE);
img = new ImageItem("yeh photo snd hui", im1, Item.LAYOUT_CENTER, "kyu nhi dikh rhi", Item.BUTTON);
frm.append(img);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
You're doing a few very odd things:
converting the byte array to a String, particularly using byte[].toString()
attempting to get an InputStream by calling Class.getResourceAsStream() with a String that has been created from the byte array.
using SMS to send an Image
Class.getResourceAsStream() is intended to take a String identifying a resource file within the MIDlet's jar file.
The correct way to do this is to get the byte[] from the BinaryMessage and use this to create an Image using Image.createImage(bytes, 0, bytes.length);
Although, as you're sending it using SMS, I'd hope it was a very small image indeed or anybody using this app will incur high costs from splitting a large image over several SMSs. Beware also that some networks limit the number of parts that an SMS can be split into.
You would be much better off researching the MMS sending functionality provided by JSR 205.
You are getting wrong the data stream, here is how you must do it:
public void create(byte[] bs)
{
try
{
im = (Image)Image.createImage(bs, 0, bs.length);
im1 = (Image)Image.createImage(im, 0, 0, i, j, Sprite.TRANS_NONE);
img = new ImageItem("yeh photo snd hui", im1, Item.LAYOUT_CENTER, "kyu nhi dikh rhi", Item.BUTTON);
frm.append(img);
}
catch (Exception e)
{
System.out.println(e);
}
}
This should work.