Hello I'm a new programmer at an high school level as a result I do not know much about programming and am getting quite a few errors which have been resolved while others I completely do not understand. I am to make a simple Check Box selection program where the user gets to pick between a variety of choices and depending on their action the image changes. The program itself compiles perfectly but when I run it however it gives me some complications. Here is my program:
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Workshop extends JPanel
implements ItemListener {
JCheckBox winterhatButton;
JCheckBox sportshatButton;
JCheckBox santahatButton;
JCheckBox redshirtButton;
JCheckBox brownshirtButton;
JCheckBox suitButton;
JCheckBox denimjeansButton;
JCheckBox blackpantsButton;
JCheckBox khakipantsButton;
StringBuffer choices;
JLabel pictureLabel;
public Workshop() {
super(new BorderLayout());
//Create the check boxes.
winterhatButton = new JCheckBox("Winter Hat");
winterhatButton.setMnemonic(KeyEvent.VK_Q);
sportshatButton = new JCheckBox("Sports Hat");
sportshatButton.setMnemonic(KeyEvent.VK_W);
santahatButton = new JCheckBox("Santa hat");
santahatButton.setMnemonic(KeyEvent.VK_E);
redshirtButton = new JCheckBox("Red Shirt");
redshirtButton.setMnemonic(KeyEvent.VK_R);
brownshirtButton = new JCheckBox("Brown Shirt");
brownshirtButton.setMnemonic(KeyEvent.VK_T);
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
blackpantsButton = new JCheckBox("Black Pants");
blackpantsButton.setMnemonic(KeyEvent.VK_I);
khakipantsButton = new JCheckBox("Khaki Pants");
khakipantsButton.setMnemonic(KeyEvent.VK_O);
//Register a listener for the check boxes.
winterhatButton.addItemListener(this);
sportshatButton.addItemListener(this);
santahatButton.addItemListener(this);
redshirtButton.addItemListener(this);
brownshirtButton.addItemListener(this);
suitButton.addItemListener(this);
denimjeansButton.addItemListener(this);
blackpantsButton.addItemListener(this);
khakipantsButton.addItemListener(this);
//Indicates
choices = new StringBuffer("---------");
//Set up the picture label
pictureLabel = new JLabel();
pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));
updatePicture();
//Put the check boxes in a column in a panel
JPanel checkPanel = new JPanel(new GridLayout(0, 1));
checkPanel.add(winterhatButton);
checkPanel.add(sportshatButton);
checkPanel.add(santahatButton);
checkPanel.add(redshirtButton);
checkPanel.add(brownshirtButton);
checkPanel.add(suitButton);
checkPanel.add(denimjeansButton);
checkPanel.add(blackpantsButton);
checkPanel.add(khakipantsButton);
add(checkPanel, BorderLayout.LINE_START);
add(pictureLabel, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the check boxes. */
public void itemStateChanged(ItemEvent e) {
int index = 0;
char c = '-';
Object source = e.getItemSelectable();
if (source == winterhatButton) {
index = 0;
c = 'q';
} else if (source == sportshatButton) {
index = 1;
c = 'w';
} else if (source == santahatButton) {
index = 2;
c = 'e';
} else if (source == redshirtButton) {
index = 3;
c = 'r';
} else if (source == brownshirtButton) {
index = 4;
c = 't';
} else if (source == suitButton) {
index = 5;
c = 'y';
} else if (source == denimjeansButton) {
index = 6;
c = 'u';
} else if (source == blackpantsButton) {
index = 7;
c = 'i';
} else if (source == khakipantsButton) {
index = 8;
c = 'o';
}
if (e.getStateChange() == ItemEvent.DESELECTED) {
c = '-';
}
//Apply the change to the string.
choices.setCharAt(index, c);
updatePicture();
}
protected void updatePicture() {
//Get the icon corresponding to the image.
ImageIcon icon = createImageIcon(
"images/bear/bear-"
+ choices.toString()
+ ".gif");
pictureLabel.setIcon(icon);
pictureLabel.setToolTipText(choices.toString());
if (icon == null) {
pictureLabel.setText("Missing Image");
} else {
pictureLabel.setText(null);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Workshop.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Build a Bear at Safeer's Workshop!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new Workshop();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Well up to this part it runs smoothly and complies but when I proceed to run the program I get this error.
> run components.Workshop
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at components.Workshop.<init>(Workshop.java:75)
at components.Workshop.createAndShowGUI(Workshop.java:195)
at components.Workshop.access$0(Workshop.java:189)
at components.Workshop$1.run(Workshop.java:209)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Might be a silly mistake however I cant seem to figure this out. Please Help and thank you
Here is the line that generates that error
private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String message;
if(messageBox.getText().length() > 0){
message = messageBox.getText();
chatBox.append(message+"\n");
printStream.println(message);//this line
printStream.flush();
//printStream.close();
messageBox.setText("");
}
}
NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.
Near the top of the code with the Public Workshop(), I am assumeing this bit,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
should maybe be,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);
Related
My storm topology (2.2.0) crashes sometimes with:
java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.io.NotSerializableException: org.apache.storm.tuple.TupleImplException
in a bolt extending the BaseStatefulWindowedBolt (my "windowbolt").
Interestingly, this seems to happen only when some throughput level is reached or network latency / packet loss occurs (I inject such network conditions on one of the storm docker containers for bench-marking purposes).
After one of this bolts' tasks failed, the others usually also do after some point and the topology is not able to recover from that failure in a state-ful way.
As the exception seems to not involve any custom classes i am quite unsure about the reason behind the failure.
Is this possibly an implementation / configuration problem on my side, or a problem / maybe even normal behavior of Apache storm under these conditions?
Error fetched by the storm cli:
{"Comp-Errors":{"windowbolt":"java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.io.NotSerializableException: org.apache.storm.tuple.TupleImpl\n\tat org.apache.storm.utils.Utils$1.run(Utils.java:409)\n\tat java.base\/java.lang.Thread.run(Unknown Source)\nCaused by: java.lang.RuntimeException: java.lang.RuntimeException: java.io.NotSerializableException: org.apache.storm.tuple.TupleImpl\n\tat org.apache.storm.executor.Executor.accept(Executor.java:290)\n\tat org.apache.storm.utils.JCQueue.consumeImpl(JCQueue.java:131)\n\tat org.apache.storm.utils.JCQueue.consume(JCQueue.java:111)\n\tat org.apache.storm.executor.bolt.BoltExecutor$1.call(BoltExecutor.java:172)\n\tat org.apache.storm.executor.bolt.BoltExecutor$1.call(BoltExecutor.java:159)\n\tat org.apache.storm.utils.Utils$1.run(Utils.java:394)\n\t... 1 more\nCaused by: java.lang.RuntimeException: java.io.NotSerializableException: org.apache.storm.tuple.TupleImpl\n\tat org.apache.storm.serialization.SerializableSerializer.write(SerializableSerializer.java:36)\n\tat com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:628)\n\tat com.esotericsoftware.kryo.serializers.CollectionSerializer.write(CollectionSerializer.java:100)\n\tat com.esotericsoftware.kryo.serializers.CollectionSerializer.write(CollectionSerializer.java:40)\n\tat com.esotericsoftware.kryo.Kryo.writeObject(Kryo.java:534)\n\tat org.apache.storm.serialization.KryoValuesSerializer.serializeInto(KryoValuesSerializer.java:38)\n\tat org.apache.storm.serialization.KryoTupleSerializer.serialize(KryoTupleSerializer.java:40)\n\tat org.apache.storm.daemon.worker.WorkerTransfer.tryTransferRemote(WorkerTransfer.java:116)\n\tat org.apache.storm.daemon.worker.WorkerState.tryTransferRemote(WorkerState.java:524)\n\tat org.apache.storm.executor.ExecutorTransfer.tryTransfer(ExecutorTransfer.java:68)\n\tat org.apache.storm.executor.bolt.BoltOutputCollectorImpl.boltEmit(BoltOutputCollectorImpl.java:112)\n\tat org.apache.storm.executor.bolt.BoltOutputCollectorImpl.emit(BoltOutputCollectorImpl.java:65)\n\tat org.apache.storm.task.OutputCollector.emit(OutputCollector.java:93)\n\tat org.apache.storm.task.OutputCollector.emit(OutputCollector.java:93)\n\tat org.apache.storm.task.OutputCollector.emit(OutputCollector.java:93)\n\tat org.apache.storm.task.OutputCollector.emit(OutputCollector.java:93)\n\tat org.apache.storm.task.OutputCollector.emit(OutputCollector.java:42)\n\tat org.apache.storm.topology.WindowedBoltExecutor.execute(WindowedBoltExecutor.java:313)\n\tat org.apache.storm.topology.PersistentWindowedBoltExecutor.execute(PersistentWindowedBoltExecutor.java:137)\n\tat org.apache.storm.topology.StatefulBoltExecutor.doExecute(StatefulBoltExecutor.java:145)\n\tat org.apache.storm.topology.StatefulBoltExecutor.handleTuple(StatefulBoltExecutor.java:137)\n\tat org.apache.storm.topology.BaseStatefulBoltExecutor.execute(BaseStatefulBoltExecutor.java:71)\n\tat org.apache.storm.executor.bolt.BoltExecutor.tupleActionFn(BoltExecutor.java:236)\n\tat org.apache.storm.executor.Executor.accept(Executor.java:283)\n\t... 6 more\nCaused by: java.io.NotSerializableException: org.apache.storm.tuple.TupleImpl\n\tat java.base\/java.io.ObjectOutputStream.writeObject0(Unknown Source)\n\tat java.base\/java.io.ObjectOutputStream.writeObject(Unknown Source)\n\tat org.apache.storm.serialization.SerializableSerializer.write(SerializableSerializer.java:33)\n\t... 29 more\n"},"Topology Name":"KafkaTopology"}
"windowbolt" implementation:
public class StatefulWindowBolt extends BaseStatefulWindowedBolt<KeyValueState<String, AvgState>> {
private OutputCollector collector;
private Counter counter;
private Counter windowCounter;
private KeyValueState<String, AvgState> state;
#Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
this.counter = context.registerCounter("WindowBolt_Executed");
this.windowCounter = context.registerCounter("WindowBolt_WindowNumber");
}
#Override
public void execute(TupleWindow inputWindow) {
long window_sum = 0;
long window_length = 0;
long ts = 0;
long max_ts = 0;
long start_event_time = inputWindow.getStartTimestamp();
long end_event_time = inputWindow.getEndTimestamp();
long partition = -1;
String note = "/";
Map<String, AvgState> map = new HashMap<String, AvgState>();
Iterator<Tuple> it = inputWindow.getIter();
while (it.hasNext()) {
Tuple tuple = it.next();
if (window_length == 0){
//same for whole window because of FieldsGrouping by partition
partition = tuple.getIntegerByField("partition");
note = tuple.getStringByField("note");
}
Long sensordata = tuple.getLongByField("sensordata");
window_sum += sensordata;
ts = tuple.getLongByField("timestamp");
if (ts > max_ts) {
max_ts = ts;
} else {
//
}
String city = tuple.getStringByField("city");
AvgState state = map.get(city);
if (state == null){
state = new AvgState(0,0);
}
map.put(city, new AvgState(state.sum+sensordata, state.count + 1));
counter.inc();
window_length++;
}
long window_avg = window_sum / window_length;
// emit the results
JSONObject json_message = new JSONObject();
json_message.put("window_avg", window_avg);
json_message.put("start_event_time", start_event_time);
json_message.put("end_event_time", end_event_time);
json_message.put("window_size", window_length);
json_message.put("last_event_ts", max_ts);
json_message.put("count_per_city", print(map));
json_message.put("partition", partition);
json_message.put("note", note);
String kafkaMessage = json_message.toString();
String kafkaKey = "window_id: " + windowCounter.getCount();
collector.emit(new Values(kafkaKey, kafkaMessage));
windowCounter.inc();
}
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("key", "message"));
}
public String print(Map<String, AvgState> map) {
StringBuilder mapAsString = new StringBuilder("{");
for (String key : map.keySet()) {
AvgState state = map.get(key);
mapAsString.append(key + "=" + state.count + ", ");
}
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
return mapAsString.toString();
}
#Override
public void initState(KeyValueState<String, AvgState> state) {
this.state = state;
}
}
in my main i set:
config.setFallBackOnJavaSerialization(true);
config.registerSerialization(AvgState.class);
I am trying to build javafx CRUD model with intellij and when I run the Main.java, Login window pops up. And when I type the correct username and password, another popup window in table so that where data can be created, read, updated and deleted.
After I typed correct password and username, Login window appeared, however, I faced NullPointerException in console as below.
When I hit Login button. I went back to two lines stated;
sortFilterTableView();
searchTextField.textProperty().addListener((observable, oldValue, newValue) -> {
there were no issues found. In other java and fxml files are all error-free. I rebuilt the project and ran it again many times but they didn't work showing me this same error. Any advice where should I begin to examine? Thank you. (Localhost is connected)
screenshot
Error in a console box
/usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java --add-modules
javafx.base,javafx.graphics --add-reads javafx.base=ALL-UNNAMED
--add-reads javafx.graphics=ALL-UNNAMED -javaagent:/snap/intellij-idea-community/232/lib/idea_rt.jar=40981:/snap/intellij-idea-community/232/bin
-Dfile.encoding=UTF-8 -p /usr/share/openjfx/lib/javafx.base.jar:/usr/share/openjfx/lib/javafx.graphics.jar:/home/marie/IdeaProjects/CosmeticsJavaFX/src/out/production/CosmeticsJavaFX:/usr/share/openjfx/lib/javafx.controls.jar:/usr/share/openjfx/lib/javafx.fxml.jar:/usr/share/openjfx/lib/javafx.media.jar:/usr/share/openjfx/lib/javafx.swing.jar:/usr/share/openjfx/lib/javafx.web.jar:/home/marie/Downloads/mariadb-java-client-2.6.0.jar
-m CosmeticsJavaFX/application.Main
wwww
wwww
Password matches
Radio button selected: null
User ID is: 9
Exception in thread "JavaFX Application Thread"
java.lang.NullPointerException at
CosmeticsJavaFX/application.DatabaseController.sortFilterTableView(DatabaseController.java:186)
at
CosmeticsJavaFX/application.DatabaseController.lambda$initialize$4(DatabaseController.java:101)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(Native
Method) at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at
javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at
javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native
Method) at
javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
at java.base/java.lang.Thread.run(Thread.java:834)
DatabaseController.java:101
#FXML
private void initialize(){
//initialize the tableView with four columns
itemIdColumn.setCellValueFactory(cellData -> cellData.getValue().itemIdProperty());
userIdColumn.setCellValueFactory(cellData -> cellData.getValue().userIdProperty());
labelColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty());
brandColumn.setCellValueFactory(cellData -> cellData.getValue().brandProperty());
setVisibleItems();
Platform.runLater(() -> {
//fill the tableView with data from observableList
try {
System.out.println("User ID is: " + userId);
tableView.setItems(getCosmeticsData());
buildCosmetics();
//line 101 below
sortFilterTableView();
//
observeRadioButtonChanges();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
});
}
DatabaseController.java:186
private void sortFilterTableView() throws SQLException {
FilteredList<Cosmetics> filteredList = new FilteredList<>(getCosmeticsData(), p -> true);
//this is line 186 below
searchTextField.textProperty().addListener((observable, oldValue, newValue) -> {
//
filteredList.setPredicate(cosmetics -> {
//if search text is empty display all cosmetics
if(newValue == null || newValue.isEmpty()){
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (cosmetics.getLabel().toLowerCase().contains(lowerCaseFilter)){
return true; // search string is a match
} else if(cosmetics.getBrand().toLowerCase().contains(lowerCaseFilter)){
return true; // search string is a match
}
return false; //does not match
});
});
SortedList<Cosmetics> sortedList = new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(sortedList);
}
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("AddressScene.fxml"));
Parent root = (Parent) fxmlLoader.load();
// open the login scene
stage.setTitle("Server Address");
stage.setScene(new Scene(root));
stage.show();
}
}
Check the Java variable searchTextField has a corresponding FXML element with a matching fx:id
<TextField fx:id="searchTextField" .........
I am making an application which uses serial communication. In SerialEvent method of that class, I am awaiting for a input from COM port, and then I want to pass it to the controller class of an .fxml screen.
Input will always be 8 bytes, and it works correctly inside that thread (I read the input and by printing it to the output, I see that the String is correct). However, when I try to pass it "in real time" to the controller class, I have a problem.
If I pass it directly, it does receieve it, but I can't invoke anything later (Not on FX Application Thread exception), I know that I can't do it that way, that I need to use Platform.runLater or similair solution, but if I use it that way, my controller class never receives that input, textField which I am trying to update stays blank.
I will copy part of the code here, and I am hoping that someone tell me what I'm doing wrong.
SERIALEVENT METHOD OF ANOTHER CLASS
#Override
public void serialEvent(SerialPortEvent spe) {
if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
byte singleData = (byte) input.read();
logText = new String(new byte[]{singleData});
bytes.add(logText);
if(bytes.size() == 8) {
for (int i = 0; i < bytes.size(); i++) {
inputText += bytes.get(i);
}
if(inputText.length() == 8) {
Platform.runLater(new Runnable() {
#Override
public void run() {
controller.getInputString(inputText);
}
});
}
bytes.clear();
inputText = "";
}
} catch (Exception e) {
logText = "Failed to read data. (" + e.toString() + ")";
controller.getInputString(logText);
}
}
}
GETINPUT METHOD OF THE CONTROLLER CLASS
#Override
public void getInputString(String input) {
firstSerialNumberField.setText(input);
}
When using it this way, my firstSerialNumberField never gets that input.
---EDIT---
SETCONTROLLER METHOD OF THE SERIALPORTLISTENER CLASS
public void setController(SerialController controller) {
this.controller = controller;
}
INITIALIZE SCREEN IN SCREEN HANDLER CLASS
serialCommunication = new SerialCommunication(this);
loader = new FXMLLoader();
loader.setLocation(getClass().getResource(path));
pane = loader.load(getClass().getResource(path).openStream());
serialController = (SerialController) loader.getController();
serialController.setScreenHandler(this);
serialController.setSerialCommunication(serialCommunication);
serialCommunication.setController(serialController);
parent = loader.getRoot();
stage = new Stage();
stage.setScene(new Scene(parent));
stage.setTitle(title);
stage.setResizable(false);
stage.sizeToScene();
stage.centerOnScreen();
stage.initModality(Modality.APPLICATION_MODAL);
stage.showAndWait();
You are passing a reference to inputText to the (inappropriately-named) getInputText() method in the controller. inputText is presumably a field in the class implementing the port listener. However, as soon as you pass it, you then set it back to an empty string:
if(inputText.length() == 8) {
Platform.runLater(new Runnable() {
#Override
public void run() {
controller.getInputString(inputText);
}
});
}
bytes.clear();
inputText = "";
Since inputText is being accessed from multiple threads, there is no guarantee as to which order things will happen: whether controller.getInputText(inputText) will execute first, or whether inputText = ""; will execute first. So you may end up setting the text field to an empty string.
What I think you intend to do is:
if(inputText.length() == 8) {
final String numberFieldText = inputText ;
Platform.runLater(new Runnable() {
#Override
public void run() {
controller.getInputString(numberFieldText);
}
});
}
or more succinctly:
if(inputText.length() == 8) {
final String numberFieldText = inputText ;
Platform.runLater(() -> controller.getInputString(numberFieldText));
}
I need to make instrument, that allows users to choose photo from Gallery. After choosing photo, it will be shown to the user in ImageBox.
Problem is, that when user chooses some photo in Gallery, Gallery closes, ImageBox stays empty. Code returns no error. Please help me to find error and solve this problem. Thank you.
Here is a code:
ImagePath = String.Empty
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
filePicker.ViewMode = PickerViewMode.Thumbnail
' Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear()
filePicker.FileTypeFilter.Add(".bmp")
filePicker.FileTypeFilter.Add(".png")
filePicker.FileTypeFilter.Add(".jpeg")
filePicker.FileTypeFilter.Add(".jpg")
filePicker.PickSingleFileAndContinue()
Dim BitmapImage = New BitmapImage()
Await BitmapImage.SetSourceAsync(filePicker)
MyPhoto.Source = BitmapImage
If you are using filePicker.PickSingleFileAndContinue() you need to add code into the App_Activated
You will notice that PickSingleFileAndContinue() is a void method will not return the picked file were as PickSingleFileAsync() will return a file.
Code block is in C#,sorry i have only limited knowledge in vb, you can find vb sample below
Similar SO Answer
C#
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
As your are using PickSingleFileAndContinue() you need to implement ContinuationManager that were you get the file you picked.
In the App.xaml.cs
public ContinuationManager ContinuationManager { get; private set; }
This will fire when the app get activated
protected async override void OnActivated(IActivatedEventArgs e)
{
base.OnActivated(e);
continuationManager = new ContinuationManager();
Frame rootFrame = CreateRootFrame();
await RestoreStatusAsync(e.PreviousExecutionState);
if(rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage));
}
var continuationEventArgs = e as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
Frame scenarioFrame = MainPage.Current.FindName("ScenarioFrame") as Frame;
if (scenarioFrame != null)
{
// Call ContinuationManager to handle continuation activation
continuationManager.Continue(continuationEventArgs, scenarioFrame);
}
}
Window.Current.Activate();
}
Usage in the page
Assume that one page of your app contains code that calls a FileOpenPicker to pick an existing file. In this class, implement the corresponding interface from the ContinuationManager helper class. When your app uses a FileOpenPicker, the interface to implement is IFileOpenPickerContinuable.
public sealed partial class Scenario1 : Page, IFileOpenPickerContinuable
{
...
//inside this you have this
private void PickAFileButton_Click(object sender, RoutedEventArgs e)
{
...
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
// Launch file open picker and caller app is suspended
// and may be terminated if required
openPicker.PickSingleFileAndContinue();
}
}
switch (args.Kind)
{
case ActivationKind.PickFileContinuation:
var fileOpenPickerPage = rootFrame.Content as IFileOpenPickerContinuable;
if (fileOpenPickerPage != null)
{
fileOpenPickerPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
}
break;
...
}
Download msdn sample here
Msdn documentation using FilePicker
I have a web application where the server returns any results in JSON format. For creating the JSON, I use the codehaus Jackson ObjectWriter, version 1.9.8.
The problem I'm having that sometimes there is an error, in the mapping, and from then on all server calls result in an error. I haven't been able to determine what causes the error, I did discover the origin.
When the exception occurs, the server returns "(was java.lang.ArrayIndexOutOfBoundsException) (through reference chain: com.onior.modm.restlet.helpers.ServiceResult["success"])", which means that the exception thrown in 'toJSON' was catched and mapped to JSON by 'toRepresentation', otherwise it would have returned empty.
I just don't know why it is sometimes failing. I will be able to use the application all morning without problems, and then suddenly I will get this error. It happens on different calls, but these calls will succeed at other times. From my point of view it seems quite random, but maybe someone can help me see the light? :)
The server result that is being mapped:
public class ServiceResult<T> {
private boolean success;
private T results = null;
private ModmServiceStatus message = null;
public ServiceResult() {
}
public ServiceResult(T results) {
this.success = true;
this.results = results;
}
public ServiceResult(boolean success, ModmServiceStatus message) {
this.success = success;
this.message = message;
}
public ServiceResult(ServiceError error) {
this(false, new ModmServiceStatus(error));
}
public static ServiceResult<ModmServiceStatus> serviceException(
ServiceError error) {
return new ServiceResult<ModmServiceStatus>(false,
new ModmServiceStatus(error.getCode(), error.getDescription()));
}
public static ServiceResult<ModmServiceStatus> dbError() {
return ServiceResult
.serviceException(ServiceError.GENERIC_DATABASE_ERROR);
}
public static ServiceResult<ModmServiceStatus> invalidJson() {
return ServiceResult
.serviceException(ServiceError.GENERIC_INVALID_JSON);
}
public static ServiceResult<ModmServiceStatus> missingEntity() {
return ServiceResult .serviceException(ServiceError.GENERIC_MISSING_OR_INCOMPLETE_ENTITY);
}
public static ServiceResult<ModmServiceStatus> entityNotFound() {
return ServiceResult
.serviceException(ServiceError.GENERIC_ENTITY_NOT_FOUND);
}
public static ServiceResult<ModmServiceStatus> entityDeleted(String entity) {
return new ServiceResult<ModmServiceStatus>(true,
new ModmServiceStatus(0, entity + " deleted."));
}
}
The mapping:
public class RestUtils {
private static final boolean PRETTY_PRINT = true;
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final ObjectWriter OBJECT_WRITER = (PRETTY_PRINT ? OBJECT_MAPPER
.writerWithDefaultPrettyPrinter() : OBJECT_MAPPER.writer());
#SuppressWarnings("unchecked")
public static <T> JacksonRepresentation<T> toJSON(T t) throws IOException {
JsonRepresentation jsonRepresentation = null;
JacksonRepresentation<T> jacksonRepresentation = null;
jsonRepresentation = new JsonRepresentation(
OBJECT_WRITER.writeValueAsString(t)); // Origin of incidental
// server error
jacksonRepresentation = new JacksonRepresentation<T>(
jsonRepresentation, (Class<T>) t.getClass());
return jacksonRepresentation;
}
public static <T> Representation toRepresentation(ServiceResult<T> ss) {
Representation representation = null;
try {
representation = RestUtils.toJSON(ss);
} catch (IOException jsonException) {
jsonException.printStackTrace();
try {
jsonException.printStackTrace();
representation = RestUtils.toJSON(jsonException.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
return representation;
}
}
The call:
RestUtils.toRepresentation(new ServiceResult<List<Group>>(groups));
The exception with stacktrace:
org.codehaus.jackson.map.JsonMappingException: (was java.lang.ArrayIndexOutOfBoundsException) (through reference chain: com.onior.modm.restlet.helpers.ServiceResult["success"])
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:218)
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:183)
at org.codehaus.jackson.map.ser.std.SerializerBase.wrapAndThrow(SerializerBase.java:140)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:158)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectWriter._configAndWriteValue(ObjectWriter.java:456)
at org.codehaus.jackson.map.ObjectWriter.writeValueAsString(ObjectWriter.java:393)
at com.onior.modm.restlet.helpers.RestUtils.toJSON(RestUtils.java:52)
at com.onior.modm.restlet.helpers.RestUtils.toRepresentation(RestUtils.java:71)
at com.onior.modm.restlet.resources.GroupCollectionResource.toJsonRead(GroupCollectionResource.java:191)
at sun.reflect.GeneratedMethodAccessor143.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.restlet.resource.ServerResource.doHandle(ServerResource.java:506)
at org.restlet.resource.ServerResource.get(ServerResource.java:707)
at org.restlet.resource.ServerResource.doHandle(ServerResource.java:589)
at org.restlet.resource.ServerResource.doNegotiatedHandle(ServerResource.java:649)
at org.restlet.resource.ServerResource.doConditionalHandle(ServerResource.java:348)
at org.restlet.resource.ServerResource.handle(ServerResource.java:952)
at org.restlet.resource.Finder.handle(Finder.java:246)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:431)
at org.restlet.routing.Router.handle(Router.java:648)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:431)
at org.restlet.routing.Router.handle(Router.java:648)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:155)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.engine.CompositeHelper.handle(CompositeHelper.java:211)
at org.restlet.engine.application.ApplicationHelper.handle(ApplicationHelper.java:84)
at org.restlet.Application.handle(Application.java:381)
at org.restlet.ext.servlet.ServletAdapter.service(ServletAdapter.java:206)
at org.restlet.ext.spring.RestletFrameworkServlet.doService(RestletFrameworkServlet.java:124)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ArrayIndexOutOfBoundsException
at org.codehaus.jackson.impl.WriterBasedGenerator.writeRaw(WriterBasedGenerator.java:577)
at org.codehaus.jackson.util.DefaultPrettyPrinter$Lf2SpacesIndenter.writeIndentation(DefaultPrettyPrinter.java:279)
at org.codehaus.jackson.util.DefaultPrettyPrinter.beforeObjectEntries(DefaultPrettyPrinter.java:98)
at org.codehaus.jackson.impl.WriterBasedGenerator._writePPFieldName(WriterBasedGenerator.java:410)
at org.codehaus.jackson.impl.WriterBasedGenerator._writeFieldName(WriterBasedGenerator.java:340)
at org.codehaus.jackson.impl.WriterBasedGenerator.writeFieldName(WriterBasedGenerator.java:217)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:444)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
... 58 more
Got the exact same ArrayIndexOutOfBoundsException with Jackson 1.9.9
After investigating, our root cause was a shared PrettyPrinter used by multiple threads.
If you look in the Jackson code for the DefaultPrettyPrinter, you will see:
/**
* Number of open levels of nesting. Used to determine amount of
* indentation to use.
*/
protected int _nesting = 0;
_nesting ends up being used to access arrays. This variable is incremented and decremented when processing object. If multiple threads decrements it, it may end up negative causing the ArrayIndexOutOfBoundsException. Once negative, it will not be ever increased again because the exception will be generated before reaching a piece of code that would increment it.
In your code, I see you have a static object writer. You probably end up with a single instance of the DefaultPrettyPrinter. If your application can concurrently produce json object, given enough time, you will get the exception.
Stéphan