Getting Java exception running the code on other machines - java

I made a project in Java, if I run the project from my machine everything works fine, but if I share the jar file and execute from another machine it does not work. I get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "10,00"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:651)
at model.components.Transaction.<init>(Transaction.java:33)
at model.events.components.AddTransactionListener.actionPerformed(AddTransactionListener.java:87)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
at java.desktop/java.awt.Component.processEvent(Component.java:6391)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
I suspect this is the code that is producing the error:
double transactionAmount = 0;
try {
if (addTransactionPanel.getAmountField().getText().equals("") || Double.parseDouble(addTransactionPanel.getAmountField().getText()) < 0.0)
throw new MyException("Enter a valid amount!");
transactionAmount = Double.parseDouble(addTransactionPanel.getAmountField().getText());
} catch(Exception e) {
errorMessage += e.getMessage() + "\n";
errorCount++;
}
addTransactionPanel.getAmountField().getText returns the text of a JTextField.
As I said before if I run the project on my machine I don't get the error (Im on Pop-os).
I made a virtual machine with Windows 10 and it works fine. I tried the code on Ubuntu which is on another disk partition and it also works.
Anyone can help me?

Without more context, I'm guessing that this is a localisation issue.
You could start by adding System.out.println(Locale.getDefault()); to your code to see what locale each platform is using.
Generally, you should be making use of JFormattedTextField or JSpinner to deal with the input format and then use their getValue method, which will actually perform the parsing, for example...
// By default, my locale is en_AU, so this is just for demonstration
// purposes, don't do this to your users
NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMANY);
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);
JFormattedTextField textField = new JFormattedTextField(format);
textField.setColumns(10);
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Will need to cast the result, as it
// returns Object by default
System.out.println(textField.getValue());
}
});
If I enter 10.10 into the field, it will output 1010, if I input 10,10 it will output 10.10
If I use Locale.getDefault() instead (ie en_AU in my case), if I enter 10.10, it will output 10.10, if I input 10,10, it will output 1010

Related

How do I catch an error in JavaFX caused by the Spinner?

I have edited this question; I couldn't find a solution to my problem, and I have decided on catching the error and handling it instead.
I'm using a Spinner controller to accept Integer values. How do I catch this kind of error java.lang.NumberFormatException ?
I'm getting this error when a user enters a character into the text edit box.
The Spinner is editable.
I really appreciate any help you can provide.
My code:
Spinner<Integer> mySpin = new Spinner<Integer>(50, 80, 50);
How can I catch the error and display a message to the user to indicate the error?
Exception in thread "JavaFX Application Thread"
java.lang.NumberFormatException: For input string: "d"
at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.valueOf(Integer.java:991)
at javafx.base/javafx.util.converter.IntegerStringConverter.fromString(IntegerStringConverter.java:49)
at javafx.base/javafx.util.converter.IntegerStringConverter.fromString(IntegerStringConverter.java:35)
at javafx.controls/javafx.scene.control.Spinner.commitValue(Spinner.java:455)
at javafx.controls/javafx.scene.control.Spinner.lambda$new$3(Spinner.java:163)
at javafx.base/com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:348)
at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
at javafx.base/javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(ReadOnlyBooleanPropertyBase.java:72)
at javafx.graphics/javafx.scene.Node$FocusedProperty.notifyListeners(Node.java:8148)
at javafx.graphics/javafx.scene.Node.setFocused(Node.java:8201)
at javafx.graphics/javafx.scene.Scene$KeyHandler.setWindowFocused(Scene.java:4026)
at javafx.graphics/javafx.scene.Scene$KeyHandler.lambda$new$0(Scene.java:4048)
at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:136)
at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
at javafx.base/javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(ReadOnlyBooleanPropertyBase.java:72)
at javafx.base/javafx.beans.property.ReadOnlyBooleanWrapper.fireValueChangedEvent(ReadOnlyBooleanWrapper.java:103)
at javafx.base/javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:111)
at javafx.base/javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:145)
at javafx.graphics/javafx.stage.Window.setFocused(Window.java:675)
at javafx.graphics/javafx.stage.Window$1.setFocused(Window.java:150)
at javafx.graphics/com.sun.javafx.stage.WindowHelper.setFocused(WindowHelper.java:112)
at javafx.graphics/com.sun.javafx.stage.WindowPeerListener.changedFocused(WindowPeerListener.java:64)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassWindowEventHandler.run(GlassWindowEventHandler.java:126)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassWindowEventHandler.run(GlassWindowEventHandler.java:40)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassWindowEventHandler.lambda$handleWindowEvent$4(GlassWindowEventHandler.java:176)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassWindowEventHandler.handleWindowEvent(GlassWindowEventHandler.java:174)
at javafx.graphics/com.sun.glass.ui.Window.handleWindowEvent(Window.java:1346)
at javafx.graphics/com.sun.glass.ui.Window.notifyFocus(Window.java:1325)
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:831)
I have solved this issue using this code as suggested by #Slaw.
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
System.out.println(throwable.getClass() + " - Error.");
});
Thanks to everyone else also.
You can catch those errors using a try catch statement when inserting elements in your spinner.

How to remove all occurrences of a substring from a string

I have a String(txt) and in this String is html code. I will search the String with txt.indexOf for
("< ac:structured-macro ac:macro-id=")
and delet it with StringBuffer(sb) sb.delete(Index, EndIndex). I will do this multiple times but when i do this with a while Loop it dosen't work and find only the index of the first element("ac:structured-macro ac:macro-id=").
Edit: The Main Problem, is that the id is always diffrent and i want to delet it too.
String txt = textArea1.getText();
/*somthing like this <p>
<p>
<br/>
</p>
<ac:structured-macro ac:macro-id="74563a55-dc09-41a1-acaa-7c6338ab4014" ac:name="unmigrated-wiki-markup"
ac:schema-version="1">
<ac:plain-text-body>
<![CDATA[
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
]]>
</ac:plain-text-body>
</ac:structured-macro>
<p>
<br/>
</p>
<ac:structured-macro ac:macro-id="bc7e6c08-82c8-4ee9-8582-b773914857f" ac:name="unmigrated-wiki-markup"
ac:schema-version="1">
<ac:plain-text-body>
<![CDATA[
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
]]>
</ac:plain-text-body>
</ac:structured-macro>
*/
int StartIndexOfMacroID = 0;
int indexEndOfMacroID = 0;
StringBuffer sb = new StringBuffer(txt);
while (StartIndexOfMacroID != -1) {
StartIndexOfMacroID = txt.indexOf("<ac:structured-macro ac:macro-id=");
indexEndOfMacroID = StartIndexOfMacroID + 159;
sb.delete(StartIndexOfMacroID, indexEndOfMacroID);
System.out.println(StartIndexOfMacroID);
);
txt = sb.toString();
System.out.println(StartIndexOfMacroID);
System.out.println(indexEndOfMacroID);
textArea2.setText(txt);
This is the output:
17
176
159
318
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: start -1, end 158, length 282
at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1724)
at java.base/java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:863)
at java.base/java.lang.StringBuffer.delete(StringBuffer.java:474)
at com.company.Main$1.actionPerformed(Main.java:115)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:270)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6651)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6416)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5026)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4858)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4858)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:778)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:727)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:751)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:749)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:748)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Thank You for your help!
Basically, the problem is to remove all occurrences of a certain html tag in the original string.
In java it may be accomplished with far less effort than your approach requires:
final String htmlContent = textArea1.getText();
final String filteredHtmlContent = htmlContent.replaceAll("<ac:structured-macro.*?</ac:structured-macro>", "");
This code replaces all occurrences of a given string with an empty string, which is equivalent to removing them.
Unfortunately, the code you posted isn't compiling. Thus, it doesn't make sense to analyze the reason it isn't working correctly. I strongly suggest to review it before sending it to stackoverflow community.
I think you would like to remove only the tag .
Because you have some line breaks
String patternText = "(<)(/)?ac:structured-macro((?!>).)*>";
Pattern pattern = Pattern.compile(patternText, Pattern.DOTALL);
String result = pattern.matcher(txt).replaceAll("");
System.out.println(result);
Explanation for the regexp:
The tags starts with (<).
You have a opening tag and a closing tag, so we need optional (/)?
Next we have the literal ac:structured-macro
Than we search for everything execpt > over multiple lines with ((?!>).)*
Last we need the closing > with >

How to filter a ArrayList according to date/time and display it in a recyclerview in Android Studio?

I have created a events list that allows users to add events, what I want to do is only display events that are not passed current date and time. I allow the user to pick a date and time which are stored as String in the format dd/MM/yy (00/00/0000) for date and HH:mm (00:00) for time in separate String variables.
I have been working on this for a nearly 3 days and still can't figure out how to do it, the concept is just on top of my head but doesn't seem to want to get out. After trying several things I have ended up with something like:
public void futureEvents() {
ArrayList<Events> futureEvents = new ArrayList<>();
long currentTime = new Date().getTime();
Log.d("CurrentTime", String.valueOf(currentTime)); // This works fine, when I Log.d I get results like 1486243693904
for(Events events : eventsList) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try { // I am forced to surround date = formatter.... code in try and catch
date = formatter.parse(events.getEventDate());
} catch (ParseException e) {
}
String eventTime = events.getEventTime();
String []tokens = eventTime.split(":");
long longEventTime = (long) ((Long.parseLong(tokens[0]) * 3.6e+6) + (Long.parseLong(tokens[1])* 1.66667e-5));
long eventTimeAndDateInLong = Long.parseLong(String.valueOf(longEventTime + date.getTime()));
if(currentTime < eventTimeAndDateInLong + 30*600000) {
futureEvents.add(events); // throws a null object reference error
}
}
adapter.filter(futureEvents);
}
I am not sure if it makes sense, but it surely doesn't work and as much as I don't want to give up, I am fed up with it not working after several attempts, I am fairly new to java and don't yet now my way around. I would really appreciate if someone could help.
Note. All I want is to filter out passed events and show the upcoming ones according to date and time.
Update --- Stack trace
02-05 11:33:47.282 19010-19010/com.example.myapp E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.myapp.SQLiteDB.EventsList_SQLDB.adapter.filter(java.util.ArrayList)' on a null object reference
at layout.Events.upcomingEvents(Events.java:352)
at layout.Events.onCreateView(Events.java:100)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1969)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:620)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
at android.view.View.measure(View.java:19861)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1375)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
at android.view.View.measure(View.java:19861)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:19861)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:19861)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19861)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:19861)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
at android.view.View.measure(View.java:19861)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:621)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
02-05 11:33:47.282 19010-19010/com.example.myapp E/UncaughtException: at android.app.ActivityThread.main(ActivityThread.java:6126)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Update -- what is adapter.filter(FutureEvents)
This is a simple filter which should if the above code works fine filter out previous events. It works if I pass it other fixed parameters e..g 01/02/2017
public void setFilter(ArrayList<Events> filterEvents) {
eventsLists = new ArrayList<>();
eventsLists.addAll(filterevents);
notifyDataSetChanged();
}
Date class provides method to test if a date is before() or after() the specified date.
Also you can get a Date object with both date and time information and then compare it with the current Date object.
Using all this you can greatly simplify your code like this :
public void futureEvents() {
ArrayList<Events> futureEvents = new ArrayList<>();
Date currentDate = new Date();
for(Events events : eventsList) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = null;
try {
date = formatter.parse(events.getEventDate() + " " + events.getEventTime());
} catch (ParseException e) {
}
if(currentDate.before(date)) {
futureEvents.add(events);
}
}
adapter.filter(futureEvents);
}
Edit : The above is still applicable for your code. But looking at your stack trace, you are getting a NullPointerException on adapter reference. Your adapter object reference is null.
Make sure you are initialising your adapter object before calling futureEvents() method.
If you want to set threshold on either side, you can modify the current date object so that it points to the date and time which is set based on your threshold. For example if you want to filter the events that occur in the next 30 minutes you can do something like this :
public void futureEvents() {
ArrayList<Events> futureEvents = new ArrayList<>();
Date currentDate = new Date();
for(Events events : eventsList) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = null;
try {
date = formatter.parse(events.getEventDate() + " " + events.getEventTime());
} catch (ParseException e) {
}
Date thresholdDate = currentDate.clone(); //makes a copy of the currentDate object
thresholdDate.setMinutes(thresholdDate .getMinutes() + 30);//Modify minutes to 30 minutes in future.
if(currentDate.before(date) && date.before(thresholdDate)) {
futureEvents.add(events);
}
}
adapter.filter(futureEvents);
}
Similarly you can modify hours, days, months or years.

Java LibreOffice Draw - Set text of a shape

I'm using Java and the LibreOffice API, and I'd like to draw rectangles and set their names, or put some text fields on them. Drawing shapes was relatively easy, but adding text is really hard. I didn't find any solution, neither in documentation nor at forums.
I am declaring the shape and text like this:
Object drawShape = xDrawFactory.createInstance("com.sun.star.drawing.RectangleShape");
XShape xDrawShape = UnoRuntime.queryInterface(XShape.class, drawShape);
xDrawShape.setSize(new Size(10000, 20000));
xDrawShape.setPosition(new Point(5000, 5000));
xDrawPage.add(xDrawShape);
XText xShapeText = UnoRuntime.queryInterface(XText.class, drawShape);
XPropertySet xShapeProps = UnoRuntime.queryInterface(XPropertySet.class, drawShape);
And then I am trying to set XText:
xShapeText.setString("ABC");
And this is where the problem appears (this exception is not clear for me even after reading the explanation from documentation):
com.sun.star.lang.DisposedException
at com.sun.star.lib.uno.environments.remote.JobQueue.removeJob(JobQueue.java:210)
at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:330)
at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:303)
at com.sun.star.lib.uno.environments.remote.JavaThreadPool.enter(JavaThreadPool.java:87)
at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge.sendRequest(java_remote_bridge.java:636)
at com.sun.star.lib.uno.bridges.java_remote.ProxyFactory$Handler.request(ProxyFactory.java:146)
at com.sun.star.lib.uno.bridges.java_remote.ProxyFactory$Handler.invoke(ProxyFactory.java:128)
at com.sun.proxy.$Proxy6.setString(Unknown Source)
at com.ericsson.stpdiagramgenerator.presentation.core.HelloTextTableShape.manipulateText(HelloTextTableShape.java:265)
at com.ericsson.stpdiagramgenerator.presentation.core.HelloTextTableShape.useWriter(HelloTextTableShape.java:65)
at com.ericsson.stpdiagramgenerator.presentation.core.HelloTextTableShape.useDocuments(HelloTextTableShape.java:52)
at com.ericsson.stpdiagramgenerator.presentation.core.HelloTextTableShape.main(HelloTextTableShape.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.io.IOException: com.sun.star.io.IOException: EOF reached - socket,host=localhost,port=8100,localHost=localhost.localdomain,localPort=34456,peerHost=localhost,peerPort=8100
at com.sun.star.lib.uno.bridges.java_remote.XConnectionInputStream_Adapter.read(XConnectionInputStream_Adapter.java:55)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at com.sun.star.lib.uno.protocols.urp.urp.readBlock(urp.java:355)
at com.sun.star.lib.uno.protocols.urp.urp.readMessage(urp.java:92)
at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDispatcher.run(java_remote_bridge.java:105)
Maybe you have another solution for inserting text/textbox/textfield on a shape with the LibreOffice API.
Your code works fine on my machine. I tested it in LibreOffice 5.1.0.3 on Windows. Here is the code I used:
com.sun.star.frame.XDesktop xDesktop = null;
// getDesktop() is from
// https://wiki.openoffice.org/wiki/API/Samples/Java/Writer/BookmarkInsertion
xDesktop = getDesktop();
com.sun.star.lang.XComponent xComponent = null;
try {
xComponent = xDesktop.getCurrentComponent();
XDrawPagesSupplier xDrawPagesSupplier =
(XDrawPagesSupplier)UnoRuntime.queryInterface(
XDrawPagesSupplier.class, xComponent);
Object drawPages = xDrawPagesSupplier.getDrawPages();
XIndexAccess xIndexedDrawPages = (XIndexAccess)
UnoRuntime.queryInterface(
XIndexAccess.class, drawPages);
Object drawPage = xIndexedDrawPages.getByIndex(0);
XMultiServiceFactory xDrawFactory =
(XMultiServiceFactory)UnoRuntime.queryInterface(
XMultiServiceFactory.class, xComponent);
Object drawShape = xDrawFactory.createInstance(
"com.sun.star.drawing.RectangleShape");
XDrawPage xDrawPage = (XDrawPage)UnoRuntime.queryInterface(
XDrawPage.class, drawPage);
XShape xDrawShape = UnoRuntime.queryInterface(XShape.class, drawShape);
xDrawShape.setSize(new Size(10000, 20000));
xDrawShape.setPosition(new Point(5000, 5000));
xDrawPage.add(xDrawShape);
XText xShapeText = UnoRuntime.queryInterface(XText.class, drawShape);
XPropertySet xShapeProps = UnoRuntime.queryInterface(
XPropertySet.class, drawShape);
xShapeText.setString("DEF");
} catch( Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
To run it, I opened a new LibreOffice Draw file, then pressed "Run Project" in NetBeans. This was the result:
It looks like the exception may be caused by a problem with connecting to the document. How exactly are you running the macro?
Related: This question is also posted at https://forum.openoffice.org/en/forum/viewtopic.php?f=20&p=395334, which contains a solution in Basic.

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String OS Kernel Simulation

I am doing a project on OS kernel simulation in java with GUI.
I have created a Jtable where I am adding the processes (tasks).
Now I am trying to execute processes with FIFO (first in first out) algorithm.
I am trying to implement the Button functionaly to execute processes with fifo algorithm. Here I'm getting the following exception raised after pressing the button.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
I might be doing something wrong here in following function
private void fifo_BtnActionPerformed(java.awt.event.ActionEvent evt) {
//DefaultTableModel model = (DefaultTableModel) processTable.getModel();
int totalNoOfProcess = p.totalProcess();
for (int i = 0; i < totalNoOfProcess; i++) {
Process cp = p.getPCB(i);
double burstTime = cp.getBurst_time();
while (burstTime > 0) {
burstTime = burstTime - cpuTime;
cp.setStatus("running");
DefaultTableModel newRow = new DefaultTableModel();
newRow.equals(model);
newRow.setValueAt(new Object[]{
(Double.parseDouble(processID_TF.getText())), processNameTF.getText(), Double.parseDouble(burstTimeTF.getText()), Double.parseDouble(priorityTF.getText()), statusTF.getText().trim()
},i, i);
//newRow.addRow(new Object[] {(Double.parseDouble(processID_TF.getText())), processNameTF.getText(), Double.parseDouble(burstTimeTF.getText()), Double.parseDouble(priorityTF.getText()), statusTF.getText().trim()});
model.removeRow(i);
//model.setValueAt(newRow, i, i);
for (int a = 0; a < 100; a++) {
model.fireTableDataChanged();
}
}
cp.setBurst_time(0);
cp.setStatus("Completed");
DefaultTableModel anotherRow = new DefaultTableModel();
anotherRow.equals(model);
anotherRow.addRow(new Object[] {
(Double.parseDouble(processID_TF.getText())), processNameTF.getText(), Double.parseDouble(burstTimeTF.getText()), Double.parseDouble(priorityTF.getText()), statusTF.getText().trim()
});
model.removeRow(i);
model.setValueAt(anotherRow, i, i);
model.fireTableDataChanged();
}
}
and here is my add_processes function
private void add_processBtnActionPerformed(java.awt.event.ActionEvent evt)
{
p.createPCB((Double.parseDouble(processID_TF.getText())), processNameTF.getText(), Double.parseDouble(burstTimeTF.getText()), Double.parseDouble(priorityTF.getText()), statusTF.getText().trim());
Process process = p.getPCB(count);
process.setId(Double.parseDouble(processID_TF.getText()));
process.setName(processNameTF.getText().trim());
process.setBurst_time(Double.parseDouble(burstTimeTF.getText()));
process.setPriority(Double.parseDouble(priorityTF.getText()));
process.setStatus(statusTF.getText());
model.addRow(new Object[]{process.getId(), process.getName(), process.getBurst_time(), process.getPriority(), process.getStatus()});
//model.fireTableDataChanged();
processID_TF.setText("");
processNameTF.setText("");
burstTimeTF.setText("");
priorityTF.setText("");
count++;
}
and here is the whole exception error which is raised after pressing fifo button . The add processes function works fine
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:992)
at java.lang.Double.parseDouble(Double.java:510)
at ahmed.riphah.OS.ProcessManagementGUI.fifo_BtnActionPerformed(ProcessManagementGUI.java:251)
at ahmed.riphah.OS.ProcessManagementGUI.access$100(ProcessManagementGUI.java:14)
at ahmed.riphah.OS.ProcessManagementGUI$2.actionPerformed(ProcessManagementGUI.java:96)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6297)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
at java.awt.Component.processEvent(Component.java:6062)
at java.awt.Container.processEvent(Container.java:2039)
at java.awt.Component.dispatchEventImpl(Component.java:4660)
at java.awt.Container.dispatchEventImpl(Container.java:2097)
at java.awt.Component.dispatchEvent(Component.java:4488)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
at java.awt.Container.dispatchEventImpl(Container.java:2083)
at java.awt.Window.dispatchEventImpl(Window.java:2489)
at java.awt.Component.dispatchEvent(Component.java:4488)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:668)
at java.awt.EventQueue.access$400(EventQueue.java:81)
at java.awt.EventQueue$2.run(EventQueue.java:627)
at java.awt.EventQueue$2.run(EventQueue.java:625)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$3.run(EventQueue.java:641)
at java.awt.EventQueue$3.run(EventQueue.java:639)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:638)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
What happens is when you click the button, one of the text fields in your GUI is empty, causing:
Double.parseDouble( aTextField.getText() );
to fail (this is what the exception is telling you).
So, two cases:
Either that text field has to be filled, in which case you could add a test when clicking the button to verify that all the fields are correctly set.
For instance:
if( processID_TF.getText().match("\\d+") ){
// proceed with normal behaviour
}else{
JOptionPane.showMessageDialog(null, "You must indicate a correct process ID.");
}
Or that field is optional, in which case you could use a try/catch block around the line of code above, and set a default value in the catch block.
For instance:
double value;
try{
value = Double.parseDouble(processID_TF.getText());
}catch(Exception e){
value = 0.; // Default value
}

Categories