assign a list object as an attribute of another class

Asked

Viewed 228 times

1

I am importing data through txt file, and I have enclosed in this class that has two attributes of type object, supplier and product. When I read the txt file, I pass as parameter only the code of the same, and try to check in the list if they exist, and if yes I add them as attribute.

However, unlike the other import methods I’ve done before, this is not adding at all.

The Catch of the exception gives me the following error :

Excessao : java.lang.NullPointerException

Exception in thread "main" java.lang.NullPointerException
at Sistema.Importa.main(Importa.java:113)  \* obj.getFornecedor().setCodigo(codigoF);  é a linha removida com comentário

follows the code of the method

public static void main(String[] args) {         

    File arquivo = new File("C:\\Users\\itach\\Desktop\\RegistroCompras.txt");
    try{

    Scanner  scanner = new Scanner(arquivo);

    DaoContasPagar dao = new DaoContasPagar();
    while(scanner.hasNextLine()){

        String s[];

        s=(scanner.nextLine().split(";"));
        CompraDeProdutos obj = new CompraDeProdutos();

        int numeronf = Integer.parseInt(s[0]);
        obj.setNotaFiscal(numeronf);
        int codigoF=Integer.parseInt(s[1]);
        obj.getFornecedor().setCodigo(codigoF); \* removi essa linha 
        for(Fornecedor lista : Dados.listaFornecedores){
            if(lista.getCodigo()==codigoF){
                obj.setFornecedor(lista);
           }
            else
                {
                    System.out.println("fornecedor nao existe");

                        } 
        }
        obj.setData(s[2]);
        int codigoP= Integer.parseInt(s[3]);

        for(Produto lista : Dados.listaProdutos){
            if(lista.getCodigo()==codigoP){
                obj.setProduto(lista);

            }
            else
                {
                    System.out.println("fornecedor nao existe");

                        } 
            }

        int quantidade=Integer.parseInt(s[4]);
        obj.setQuantidade(quantidade);
        dao.NovaCompra(obj);

        }

    }
    catch(Exception e){

    }
}

and the class from which I am generating a new object, with the imported data.

public class CompraDeProdutos {
    private int notaFiscal;
    private Produto produto;
    private String data;
    private Fornecedor fornecedor;
    private int quantidade;
    private double totalApagar;

    public List <Produto> getLista(){
        return Dados.listaProdutos;
    }

    public CompraDeProdutos(int notaFiscal, Produto produto, String data, Fornecedor fornecedor, int quantidade, double totalApagar) {
        this.notaFiscal = notaFiscal;
        this.produto = produto;
        this.data = data;
        this.fornecedor = fornecedor;
        this.quantidade = quantidade;
        this.totalApagar = totalApagar;
    }



    public int getNotaFiscal() {
        return notaFiscal;
    }

    public void setNotaFiscal(int notaFiscal) {
        this.notaFiscal = notaFiscal;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public double getTotalApagar() {
        return totalApagar;
    }

    public void setTotalApagar(int totalApagar) {
        this.totalApagar = totalApagar;
    }

    public Produto getProduto() {
        return produto;
    }

    public void setProduto(Produto produto) {
        this.produto = produto;
    }

    public Fornecedor getFornecedor() {
        return fornecedor;
    }

    public void setFornecedor(Fornecedor fornecedor) {
        this.fornecedor =fornecedor;
    }

    public CompraDeProdutos() {
    }



    public int getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(int quantidade) {
        this.quantidade = quantidade;
    }

    @Override
    public String toString() {
        return  "" + getNotaFiscal() + ";" +getFornecedor().getCodigo()+";" + getData() + ";" + getProduto()+ ";" + getQuantidade() + ";"+getTotalApagar()+";";
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 11 * hash + this.notaFiscal;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final CompraDeProdutos other = (CompraDeProdutos) obj;
        if (this.notaFiscal != other.notaFiscal) {
            return false;
        }
        return true;
    }





}
  • Adds full stack of errors, only with this line makes it difficult to detect the problem.

  • Tip: if not treat exception, do not use empty catch.

  • I edited the code and removed the troublesome line. now you are successfully adding :D

  • Daniel the error was evident, never instantiates an object Fornecedor, logo, is accessing a null object with that line in the class CompraDeProdutos

  • 1

    Removing the line does not fix the problem, you are just postponing it at this point.

  • Got it !! sorry for the thoughtless question :s how I do this check so if I can’t instantiate this object ?

  • 1

    The correct question is why is creating an empty object if you made a constructor passing data? I don’t know the logic applied to your application, but creating an empty product purchase doesn’t make much sense, looking at the logical side of a shopping program.

  • I created this empty object to be able to set its data by reading the txt file only, reading each data of txt separated by ";" and adding to the respective attribute. In this import method I would instantiate an object for each row handles the respective attributes of the purchase.

  • So you need to be aware when trying to access Vendor and Product within this class, because as Voce creates it empty, these 2 objects are never instantiated, and whenever they are accessed, returned this error. Check if it is null before accessing.

  • if I pass only these two parameters in the constructor they will be instantiated automatically when creating a class object?

  • No, you need to create this instance. There are two loops in the code that fill these objects, ja. Just be careful when accessing them in class, checking if they are not null before.

  • I will think here how to do this in the right way. But thank you very much for your help and for the time willing with me :D

Show 7 more comments
No answers

Browser other questions tagged

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