NullPointerException in Intelli J javafx CRUD - intellij-idea

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" .........

Related

"java[934:22850] +[CATransaction synchronize] called within transaction" when a FileChooser dialog box is displayed

In running a Java program, using IntelliJ Community Edition 2021.2, I am seeing console output "java[934:22850] +[CATransaction synchronize] called within transaction" when a FileChooser dialog box is displayed. The dialog appears to work OK, but I'm puzzled about the message.
MacOS 13.0.1 (Ventura);
IntelliJ Community Edition 2021.2;
JDK 15.0.2;
JavaFX 15.0.1+1
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.*;
public class Main extends Application {
// ..................... and now it's time for the main routine .....................
#Override
public void start(Stage primaryStage) {
// we need a FileChooser
FileChooser myChooser = new FileChooser();
// set up a controlled exit
primaryStage.setOnCloseRequest(e -> {
e.consume();
primaryStage.close();
});
// define the main scene's building blocks
VBox root = new VBox(5); // the spacing is between each element in the VBox
Scene mainScene = new Scene(root, 650, 300);
// just one button in the scene
Button websiteSupportButton = new Button("Process file");
websiteSupportButton.setMinWidth(150);
root.getChildren().add(websiteSupportButton);
websiteSupportButton.setOnAction(e -> processFiles(primaryStage, myChooser));
// and now we're ready to associate the root Scene with the primary stage, and show it
primaryStage.setX(20);
primaryStage.setY(20);
primaryStage.setScene(mainScene);
primaryStage.setTitle("Error test");
primaryStage.show();
}
// .................................. tool scenes ..................................
// stuff moved from WebsiteSupport, and severely cut down - select an input file.
private static void processFiles(Stage myStage, FileChooser myChooser) {
File inputFile;
// need to select an input file - displaying this dialog causes multiple "java[1334:69043] +[CATransaction synchronize] called within transaction" messages
inputFile = myChooser.showOpenDialog(myStage);
if (inputFile != null) {
System.out.println(" file processed");
}
}
// .......................................... standard stuff ..........................................
public static void main(String[] args) {
launch(args);
}
}
I tried your code on:
OS X (intel) 13.0.1
JavaFX 19
OpenJDK 19.0.1
It received the same error message (multiple times for a single call):
java[34308:361725] +[CATransaction synchronize] called within transaction
I believe it occurs every time the file chooser showOpenDialog method is invoked in this configuration. A minimal example which replicates the issue on execution is:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileChooserCATransactionLogGeneratorApp extends Application {
#Override
public void start(Stage stage) {
stage.setScene(new Scene(new Group()));
stage.show();
FileChooser myChooser = new FileChooser();
myChooser.showOpenDialog(stage);
}
public static void main(String[] args) {
launch(args);
}
}
I advise filing a bug report.
If you do file a bug report and a bug id is generated, you can add a link to the bug report as a comment or an edit on this answer.

Application crash while using spinner

This method is to get the inputs that includes three EditText boxes and one spinner which is populated from string-array.The click of the button is the trigger for undertaking the calculations. While the OnClick method is pressed the application crashes. The code is as follows
package biz.avksons.siddharth.hydro_basic_calc;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class UoE extends AppCompatActivity {
// Define variables for Spinner here
Spinner spinner_1;
String spin_select;
boolean dbug=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uoe);
}
// ************************************************************************************
// Start the method to calculate the units of electricity here
public void onUoECalc_ButtonClick(View v) {
/* Define Custom method for calculating the Units of electricity on clicking the Calculate button*/
//Processing variable for count
boolean flag = false; // Used to check if the inputs done in the EditText are valid or not, else there will an exception which would lead to application crash
/* Initiate the Variables here*/
//-----------------------------------------------------
//Allocate the ids of EditText to the variables for further use
EditText et_capacity = (EditText) findViewById(R.id.et_uoe_capacity);
EditText et_plf = (EditText) findViewById(R.id.et_uoe_plf);
EditText et_availability = (EditText) findViewById(R.id.et_uoe_availability);
EditText et_energy = (EditText) findViewById(R.id.et_uoe_mus);
//Variable for deciding Timeperiod
Double time_period = 365.00;
//---DEBUG <code></code>
if (dbug)
{
Toast.makeText(this, "Spiner selection : " + spin_select, Toast.LENGTH_SHORT).show();
}
//Set flag to true only if the inputs in the two edittext, discharge and head are sensible inputs
if (checkedittext(et_capacity) && checkedittext(et_plf) && checkedittext(et_availability)) {
flag = true;
} else {
//If the inputs in discharge are not sensible then display the message to input a sensible input before moving further
Toast.makeText(this, "Please enter valid inputs", Toast.LENGTH_LONG).show();
// Set the EditText box of the output to blank if the inputs are not valid as tested in the above statements
et_capacity.setText("");
}
// do this operation only if the flag is set to true which are tested above
if (flag == true) {
//-------Initiating Spinner here
addListenerOnSpinnerItemSelection();
// Set selection default for Spinner here
// spinner_1.setSelection(1);
//--------Allocation of Spin Button Here-------------
if (dbug)
{
Toast.makeText(this, "Spin_select"+ spin_select, Toast.LENGTH_SHORT).show();
}
switch (spin_select) {
case "1 yr":
time_period = 365.00;
case "6 mon":
time_period = 180.00;
case "3 mon":
time_period = 90.00;
}
//-------End of Spin Button--------------
//Assign the values here
Double d_capacity = Double.parseDouble(et_capacity.getText().toString());
Double d_plf = Double.parseDouble(et_plf.getText().toString());
Double d_availability = Double.parseDouble(et_availability.getText().toString());
//-DEBUG Code----
if(dbug)
{
Toast.makeText(this, "Time Period selected" + time_period.toString(), Toast.LENGTH_SHORT).show();
}
Double d_energy = Double.valueOf((d_capacity * 1000 * 24 * time_period * d_plf * d_availability) / 1000000);
et_energy.setText(Double.toString(Math.round(d_energy))); // In MW
// capacity.setText(String.format(".2%f",Double.toString(C)));
}
}
//Method to check for validity of contents in edittext
public boolean checkedittext(EditText edtxt) {
if (edtxt.getText().toString().matches("")) {
return false;
} else {
return true;
}
}
//--------Method to get the selected option from Spinner
public void addListenerOnSpinnerItemSelection() {
//------Declare a variable on Spinner and allocate the id here
spinner_1 = (Spinner) findViewById(R.id.spin_uoe_period);
spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
spin_select = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void onHelp_UoE(View v)
{
Toast.makeText(this,"Please enter valid figures in the boxes mentioned and select the period you are interested in; from the dropdown menu before pressing calculate",Toast.LENGTH_LONG).show();
}
}
The error in Logcat is as follows
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4240) 
at android.view.View$PerformClick.run(View.java:17721) 
at android.os.Handler.handleCallback(Handler.java:730) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at biz.avksons.siddharth.hydro_basic_calc.UoE.onUoECalc_ButtonClick(UoE.java:84)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4240) 
at android.view.View$PerformClick.run(View.java:17721) 
at android.os.Handler.handleCallback(Handler.java:730) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
I tried to find the NullPointerException error which as per the code suggests that the spinner_select variable is not initialized. My understanding tells me that the spinner_select variable should be initialized every time the method is called.
Request for assistance..Thank You
I hope you have missed
break;
in switch case statement

Add custom console to Eclipse console list

Based on this tutorial, I'm creating an Eclipse plugin which provides a new console, The console is added to the view and I can print messages there, but for some reason it is not added to the consoles list (the dropdown list in the view's corner, see image below).
This is how I'm creating the console:
public void createConsole(String name) {
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager consoleManager = plugin.getConsoleManager();
console = new MessageConsole(name, null);
consoleManager.addConsoles(new IConsole[]{console});
}
And then I can print messages using this method:
public void print(String msg) {
MessageConsoleStream out = console.newMessageStream();
out.println(msg);
}
Also I'm using this method to bring the console view to the front:
public void bringToFront() {
try{
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
String id = IConsoleConstants.ID_CONSOLE_VIEW;
IConsoleView view = (IConsoleView) page.showView(id);
view.display(console);
} catch(PartInitException e) {
e.printStackTrace();
}
}
Any suggestions?
To add a new type of console to the console view, you need to provide a consoleFactories extension:
<extension
point="org.eclipse.ui.console.consoleFactories">
<consoleFactory
class="com.example.MyConsoleFactory"
icon="icons/etool16/my-console.png"
label="My Console">
</consoleFactory>
</extension>
The factory class needs to provide an implementation for openConsole in which your console is created and shown, just like you did in your existing code:
class ConsoleFactory implements IConsoleFactory {
#Override
public void openConsole() {
IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager();
MyConsole console = new MyConsole();
consoleManager.addConsoles( new IConsole[] { console } );
consoleManager.showConsoleView( console );
}
}

How to get path of current selected file in Eclipse plugin development

I am opening an Editor with Open with menu in Eclipse.But i am not able to get path of current selected file.Sometimes it gives proper path but sometimes throws null pointer Exception.
I am writing following code to get selected file path.
IWorkbenchPage iwPage=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
System.err.println("iwpage::"+iwPage);
ISelection selection=iwPage.getSelection();
System.err.println("selection::::testtttt"+selection.toString());
if(selection!=null && selection instanceof IStructuredSelection)
{
IStructuredSelection selectedFileSelection = (IStructuredSelection) selection;
System.out.println(selection.toString());
Object obj = selectedFileSelection.getFirstElement();
selectedFile=(IResource)obj;
System.err.println("selection::::"+selectedFile.getLocation().toString());
String html=selectedFile.getLocation().toString().replace(" ","%20");
String html_file="file:///"+html;
return html_file;
}
I found an answer in the Eclipse forum that seems easier and works for me so far.
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window =
workbench == null ? null : workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage =
window == null ? null : window.getActivePage();
IEditorPart editor =
activePage == null ? null : activePage.getActiveEditor();
IEditorInput input =
editor == null ? null : editor.getEditorInput();
IPath path = input instanceof FileEditorInput
? ((FileEditorInput)input).getPath()
: null;
if (path != null)
{
// Do something with path.
}
Some of those classes required new project references, so here's a list of all my imports for that class. Not all of them are related to this snippet, of course.
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.osgi.framework.Bundle;
You can ask the active editor for the path of the underlying file. Just register an IPartListener to your active IWorkbenchPage and ask withing this listener when activating a part. Here is a snippet
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.addPartListener(new IPartListener() {
#Override
public void partOpened(IWorkbenchPart part) {
// TODO Auto-generated method stub
}
#Override
public void partDeactivated(IWorkbenchPart part) {
// TODO Auto-generated method stub
}
#Override
public void partClosed(IWorkbenchPart part) {
// TODO Auto-generated method stub
}
#Override
public void partBroughtToTop(IWorkbenchPart part) {
if (part instanceof IEditorPart) {
if (((IEditorPart) part).getEditorInput() instanceof IFileEditorInput) {
IFile file = ((IFileEditorInput) ((EditorPart) part)
.getEditorInput()).getFile();
System.out.println(file.getLocation());
}
}
}
#Override
public void partActivated(IWorkbenchPart part) {
// TODO Auto-generated method stub
}
});

Eclipse Plugin Development : How to change file attributes of selected files?

I am trying to create an eclipse plugin to change the selected files to read only. Created popup menu sample plugin project which when executed shows a message "New Action was executed"
I am stuck at next step.
How to get list of files selected, and change file attributes ?
I don't have the time to test the following properly, but it is probably a good starting point:
public class SetFileToROHandler extends AbstractHandler implements IHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
final ISelection s = HandlerUtil.getCurrentSelectionChecked(event);
if (!(s instanceof IStructuredSelection))
return null;
final IStructuredSelection ss = (IStructuredSelection) s;
for (final Object o : ss.toArray()) {
if (!(o instanceof IFile)) {
continue;
}
IFile f = (IFile) o;
f.setReadOnly(true);
}
return null;
}
}