Nullpointer Java Even if you initialized the variable

Asked

Viewed 184 times

-2

i am having a problem to set a label of another controller, my project is structured as follows: Filmeoverviewcontroller, is the Overview that contains a tableview, in that tableview you can select the movie and etc, then I created an Handle for a button that takes these attributes of the movies and there is another class called Room, in which there are some attributes (if it is 3d, capacity and etc) however, I can not in any way use the attributes contained in that other room, even by initializing the same, I always have Nullpointer or something like that, someone knows what I can do to fix it?

Follows the code of the class Filmeoverviewcontroller and the class room respectively:

public class FilmeOverviewController {

    @FXML
    private TableView<Filmes> filmeTable;
    @FXML
    private TableColumn<Filmes, String> nomeColumn;
    @FXML
    private TableColumn<Filmes, String> categoriaColumn;
    @FXML
    private TableColumn<Filmes, String> salaColumn;

    @FXML
    private Label nomeLabel;
    @FXML
    private Label salaLabel;
    @FXML
    private Label categoriaLabel;
    @FXML
    private Label diretorLabel;
    @FXML
    private Label duracaoLabel;
    @FXML
    private Label protagonistaLabel;
    @FXML
    private Label classificacaoLabel;
    @FXML
    private Label capacidadeLabel;
    @FXML
    private Label disponivelLabel;
    @FXML
    private Label is3dLabel;
    @FXML
    private JFXButton venderIngresso;


    // referencia a classe main
    private MainApp mainApp;


    public FilmeOverviewController() {
    }

    @FXML
    private void initialize() {
        //Inicia a tableview com tres colunas.
        nomeColumn.setCellValueFactory(cellData -> cellData.getValue().nomeProperty());
        categoriaColumn.setCellValueFactory(cellData -> cellData.getValue().categoriaProperty());
        salaColumn.setCellValueFactory(cellData -> cellData.getValue().getSala());
        // limpando os detalhes
        showFilmeDetails(null);
        // adicionando funcao
        filmeTable.getSelectionModel().selectedItemProperty()
        .addListener((observable, oldValue, newValue) -> showFilmeDetails(newValue));

    }

    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;

        //adiciona uma observable list
        filmeTable.setItems(mainApp.getfilmeDados());
    }


    private void showFilmeDetails(Filmes filme) {
        if (filme != null) {
            nomeLabel.setText(filme.getNome());
            categoriaLabel.setText(filme.getCategoria());
            duracaoLabel.setText(filme.getDuracao());
            protagonistaLabel.setText(filme.getProtagonista());
            classificacaoLabel.setText(filme.getClassificacao());
            diretorLabel.setText(filme.getDiretor());
            salaLabel.setText(filme.getSalaNumero());
            capacidadeLabel.setText(Integer.toString(filme.getCapacidade()));
            disponivelLabel.setText(Integer.toString(filme.getDisp()));
            if (filme.get3D() == true) {
                is3dLabel.setText("Sim");
            } else {
                is3dLabel.setText("Não");
            }
        } else {
            nomeLabel.setText("");
            categoriaLabel.setText("");
            duracaoLabel.setText("");
            protagonistaLabel.setText("");
            classificacaoLabel.setText("");
            diretorLabel.setText("");
            salaLabel.setText("");
            capacidadeLabel.setText("");
            disponivelLabel.setText("");
            is3dLabel.setText("");
        }
    }

    @FXML
    private void handleDeletarFilme() {
        int selectedIndex = filmeTable.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0) {
            filmeTable.getItems().remove(selectedIndex);
        } else {
            Alert alerta = new Alert(AlertType.WARNING);
            alerta.setTitle("Nenhum filme selecionado");
            alerta.setHeaderText("Nenhuma Selecao");
            alerta.setContentText("Por favor selecione um filme para deletar");
            alerta.showAndWait();
        }

    }

    @FXML
    private void handleNovoFilme() {
        Filmes tempFilme = new Filmes("Nome","Categoria");
        boolean clicado = mainApp.showEditarFilmeDialog(tempFilme);
        if (clicado) {
            mainApp.getfilmeDados().add(tempFilme);
        }

    }

    @FXML
    private void handleEditarFilme() {
        Filmes filmeSelecionado = filmeTable.getSelectionModel().getSelectedItem();
        if(filmeSelecionado != null) {
            boolean clicado = mainApp.showEditarFilmeDialog(filmeSelecionado);
            if(clicado) {
                showFilmeDetails(filmeSelecionado);
            }
        }else {
            //se nada for selecionado
            Alert alerta = new Alert(AlertType.WARNING);
            alerta.initOwner(mainApp.getPrimaryStage());
            alerta.setTitle("Nenhuma selecao");
            alerta.setHeaderText("Nenhum filme selecionado");
            alerta.setContentText("Por favor selecione algum filme.");
            alerta.showAndWait();
        }
    }
    @FXML
    public void handleVenderIngresso() throws IOException {

          Filmes filmeSelecionado = filmeTable.getSelectionModel().getSelectedItem();
          FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("resources/VenderIngresso.fxml"));
            AnchorPane pane = (AnchorPane) loader.load();
            //criar o stage

            Stage dialogStage = new Stage();
            dialogStage.setTitle("Vender Ingresso");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            dialogStage.initOwner(mainApp.getPrimaryStage());
            Scene scene = new Scene(pane);
            dialogStage.setScene(scene);

            //chamando o controlador

            VenderIngressoController controller = loader.getController();
            controller.setDialogStage(dialogStage);


            //mostrando o dialog e esperando ate fecharem
            dialogStage.showAndWait();

        }
}

public class Sala {
    private boolean e3d;
    private int assentosMax;
    private int assentosDisp;
    private final StringProperty numeroProperty = new SimpleStringProperty();


    public Sala(boolean e3d, int assentosMax, int assentosDisp, String numero) {
        setNumero(numero);
        e3d = this.e3d;
        assentosMax = this.assentosMax;
        assentosDisp = this.assentosDisp;
    }
    public boolean is3d() {
        return e3d;
    }
    public void setE3d(boolean e3d) {
        this.e3d = e3d;
    }
    public int getAssentosMax() {
        return assentosMax;
    }
    public void setAssentosMax(int assentosMax) {
        this.assentosMax = assentosMax;
    }
    public int getAssentosDisp() {
        return assentosDisp;
    }
    public void setAssentosDisp(int assentosDisp) {
        this.assentosDisp = assentosDisp;
    }
    public StringProperty numeroProperty() {
        return numeroProperty;
    }
    public final String getNumero() {
        return numeroProperty.get();
    }
    public final void setNumero(String numero) {
        numeroProperty().set(numero);
    }



}

So, I created a controller in which I want to take the attributes of the selected movie and put in its textfield:

public class VenderIngressoController {
    @FXML
    private Label tituloLabel;

    @FXML
    private Label salaLabel;

    @FXML
    private Label categoriaLabel;

    @FXML
    private Label diretorLabel;

    @FXML
    private Label duracaoLabel;

    @FXML
    private Label protagonistaLabel;

    @FXML
    private Label classificacaoLabel;

    @FXML
    private Label e3dLabel;

    @FXML
    private JFXButton gerarIngresso;

    @FXML
    private JFXButton cancelarIngresso;

    @FXML
    private CheckBox meiaEntradaBox;

    @FXML
    private JFXTextField precoEspecialField;

    @FXML
    private CheckBox checkPrecoEspecial;

    private Filmes filme;

    private Stage dialogStage;
    private int precoEspecial;

    public int getPrecoEspecial() {
        return precoEspecial;
    }
    public void setPrecoEspecial(int precoEspecial) {
        this.precoEspecial = precoEspecial;
    }
    public int getPreco() {
        return preco;
    }
    public void setPreco(int preco) {
        this.preco = preco;
    }
    public int getMeiaEntrada() {
        return meiaEntrada;
    }
    public void setMeiaEntrada(int meiaEntrada) {
        this.meiaEntrada = meiaEntrada;
    }

    private int preco;
    private int meiaEntrada;


    @FXML
    private void initialize() {

    }
    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;

    }

    public void VenderIngresso(Filmes filme) {
        this.filme = filme;
        tituloLabel.setText(filme.getNome());
        salaLabel.setText(filme.getSalaNumero());
        categoriaLabel.setText(filme.getCategoria());
        diretorLabel.setText(filme.getDiretor());
        duracaoLabel.setText(filme.getDuracao());
        protagonistaLabel.setText(filme.getProtagonista());
        classificacaoLabel.setText(filme.getClassificacao());
        if (filme.get3D() == true) {
            e3dLabel.setText("Sim");
        } else {
            e3dLabel.setText("Não");
        }

    }
    public void setCategoria (String nome) {
        categoriaLabel.setText(nome);
    }
    @FXML
    void handleCancelarIngresso(ActionEvent event) {
        dialogStage.close();
    }

    @FXML
    void handleGerarIngresso(ActionEvent event) {

    }

}

So what I tried to do was this: venderIngressoController.setCategoria(filmeSelecionado.getCategoria()); However, it returns me a Nullpointer, does anyone know what I can do to fix it? I tried the American stackoverflow and could not find a similar doubt with 2 controllers. Edit: Stacktrace

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    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 sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 52 more
Caused by: java.lang.NullPointerException
    at projeto.resources.EditarFilmeController.setFilme(EditarFilmeController.java:65)
    at projeto.MainApp.showEditarFilmeDialog(MainApp.java:105)
    at projeto.resources.FilmeOverviewController.handleEditarFilme(FilmeOverviewController.java:145)
    ... 62 more

The same way I put it up there, I tried to use capacidadeField.setText(Integer.toString(filme.getCapacidade())); in another class and had the same problem, however, I can’t find out since I initialized the variable

  • Where is the line venderIngressosController.setCategoria(filmeSelecionado.getCategoria());? I couldn’t find it in the source code provided.

  • I took it out to test if it was this call that caused the error and really it was, I’ll post the stacktrace add

  • I had a similar problem once and passing information from one controller to the other is a bit difficult. There is the option to create a controller with a parameter but it wouldn’t help you much. Using a database maybe?

  • NPE can also happen if you der setText(null), ie.getCategoria() returns null. This does not seem to be the case but it is only for resaltar that may not be variables initialization problems.

1 answer

0


Hello, the best way to send information from a Controllers1 to a Controllers2 is to use the constructors of the classes by passing the Controllers1 parameter in the Controller construction2. This way you can access any public method and variable of Controllers1 in Controllers2.

example:

/**
 * Neste exemplo o que vou fazer é pegar a informação de um 
 * textField da classe Controller1 e mostrar na classe Controller2 
 * usando o metodo getText() da classe Controller1 na classe Controller2
 **/ 

//class Controladora 1
public class Controller1{

@FXML
private TextField txtNome;

@FXML
private Button btnEnviar;

public Controller1(){}

@FXML
void actionBtnEnviar(ActionEvent evt){ //Action do botão
   new Controller2(Controller1.this); //Chamada da classe Controller2 passando class Controller1
}

//Método pra obter o valor do TextField
public String getText(){
  return txtNome.getText();//retornar o valor do TextField
}

}

//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

//Controladora 2
public class Controller2{

@FXML
private TextField txtNome;


public Controller1 controller1;

//Contructor da classe
public Controller2(Controller1 controller1){

 this.controller1 = controller1;
}

 @FXML
 private void initialize() {
    if(controller1 !=null)// verificar controller1 nao esteja vacio
      System.out.println(controller1.getText());// print na console o valor do textField

     else
      System.out.println("Texto vacio");//print vacio caso controller1 esteja vacio
 }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.