Nullpointerexception error using Boolean type

Asked

Viewed 194 times

0

I’m having problems again with this project, the application runs normally opens the screen to register and everything, but when you click on the button to save it simply closes the app, but the firebase console is registered the data... I have already analyzed and I did not find the error, someone there knows where this error is ?

Thank you in advance...

//Error:

  java.lang.NullPointerException: Attempt to invoke virtual method 
  'boolean    java.lang.Boolean.booleanValue()' on a null object reference at
   com.example.matheus.kypyy.MainActivity$2.onClick(MainActivity.java:98)

//Class of Users

public class Usuarios {

private String nome;
private String Data;
private String Rg;
private String Cpf;
private String Endereco;
private String Doenca;
private String Profissao;

public void Usuarios(){

}

public String getCpf() {
    return Cpf;
}

public void setCpf(String cpf) {
    Cpf = cpf;
}

public String getData() {
    return Data;
}

public void setData(String data) {
    Data = data;
}

public String getDoenca() {
    return Doenca;
}

public void setDoenca(String doenca) {
    Doenca = doenca;
}

public String getEndereco() {
    return Endereco;
}

public void setEndereco(String endereco) {
    Endereco = endereco;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getProfissao() {
    return Profissao;
}

public void setProfissao(String profissao) {
    Profissao = profissao;
}

public String getRg() {
    return Rg;
}

public void setRg(String rg) {
    Rg = rg;
 }
}

//Firebase BD Class

public class FireHelper {
DatabaseReference bd;
Boolean saved;
ArrayList<Usuarios> usuarioss = new ArrayList<>();

public FireHelper(DatabaseReference bd) {
    this.bd = bd;
}
public Boolean save(Usuarios usuarios){
    if(usuarios == null){
        saved = false;
    }
    else
    {
        try{
            bd.child("Usuarios").push().setValue(usuarios);
        }catch (DatabaseException e){
            e.printStackTrace();
            saved = false;
        }
    }
    return saved;
}

private void fetchData(DataSnapshot dataSnapshot){
    usuarioss.clear();

    for(DataSnapshot ds : dataSnapshot.getChildren()){
        Usuarios usuarios = ds.getValue(Usuarios.class);
        usuarioss.add(usuarios);
    }
}

public ArrayList<Usuarios> retorno(){
    bd.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            fetchData(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            fetchData(dataSnapshot);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return usuarioss;
 }
}

// Main class where the data will be displayed

 public class MainActivity extends AppCompatActivity {
DatabaseReference bd;
FireHelper helper;
AdapterCustom adapter;
ListView lv;
EditText textViewNome, textViewData, textViewRg, textViewCpf, textViewEndereco, textViewDoenca, textViewProfissao;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //Banco de dados
    bd = FirebaseDatabase.getInstance().getReference();
    helper = new FireHelper(bd);
    //layout
    lv = (ListView) findViewById(R.id.lv);
    //Adaptador
    adapter = new AdapterCustom(this, helper.retorno());
    lv.setAdapter(adapter);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            displayInputDialog();
        }
    });
}



private void displayInputDialog() {
    Dialog d = new Dialog(this);
    d.setTitle("Salvar no banco de dados");
    d.setContentView(R.layout.input_dialog);

    //Declarando objetos
    final TextView textViewNome = (TextView) d.findViewById(R.id.editTextNome);
    final TextView textViewData = (TextView) d.findViewById(R.id.editTextData);
    final TextView textViewRg = (TextView) d.findViewById(R.id.editTextRg);
    final TextView textViewCpf = (TextView) d.findViewById(R.id.editTextCpf);
    final TextView textViewEndereco = (TextView) d.findViewById(R.id.editTextEndereco);
    final TextView textViewDoenca = (TextView) d.findViewById(R.id.editTextDoenca);
    final TextView textViewProfissao = (TextView) d.findViewById(R.id.editTextProfissao);

    Button saveButton = (Button) d.findViewById(R.id.savebutton);


    //Salvar...
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String nome = textViewNome.getText().toString();
            String data = textViewData.getText().toString();
            String rg = textViewRg.getText().toString();
            String cpf = textViewCpf.getText().toString();
            String endereco = textViewEndereco.getText().toString();
            String doenca = textViewDoenca.getText().toString();
            String profissao = textViewProfissao.getText().toString();
            Usuarios u = new Usuarios();
            u.setNome(nome);
            u.setData(data);
            u.setRg(rg);
            u.setCpf(cpf);
            u.setEndereco(endereco);
            u.setDoenca(doenca);
            u.setProfissao(profissao);

            if (nome != null && nome.length() > 0) {
                if (helper.save(u)) {
                    textViewNome.setText("");
                    textViewData.setText("");
                    textViewRg.setText("");
                    textViewCpf.setText("");
                    textViewEndereco.setText("");
                    textViewDoenca.setText("");
                    textViewProfissao.setText("");

                    adapter = new AdapterCustom(MainActivity.this, helper.retorno());
                    lv.setAdapter(adapter);

                } else {
                    Toast.makeText(MainActivity.this, "sem dados", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
    d.show();
  }

}

//Class of the Adapter

public class AdapterCustom extends BaseAdapter {
Context c;
ArrayList<Usuarios> usuarioss;

public AdapterCustom(Context c, ArrayList<Usuarios> usuarioss) {
    this.c = c;
    this.usuarioss = usuarioss;
}

@Override
public int getCount() {
    return usuarioss.size();
}

@Override
public Object getItem(int position) {
    return usuarioss.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView== null){
        convertView = LayoutInflater.from(c).inflate(R.layout.model,parent,false);
    }
    //Declarando objetos
    TextView textViewNome = (TextView)convertView.findViewById(R.id.textViewNome);
    TextView textViewData = (TextView)convertView.findViewById(R.id.textViewData);
    TextView textViewRg = (TextView)convertView.findViewById(R.id.textViewRg);
    TextView textViewCpf = (TextView)convertView.findViewById(R.id.textViewCpf);
    TextView textViewEndereco = (TextView)convertView.findViewById(R.id.textViewEndereco);
    TextView textViewDoenca = (TextView)convertView.findViewById(R.id.textViewDoenca);
    TextView textViewProfissao = (TextView)convertView.findViewById(R.id.textViewProfissao);

    final Usuarios u = (Usuarios) this.getItem(position);

    textViewNome.setText(u.getNome());
    textViewData.setText(u.getData());
    textViewRg.setText(u.getRg());
    textViewCpf.setText(u.getCpf());
    textViewEndereco.setText(u.getEndereco());
    textViewDoenca.setText(u.getDoenca());
    textViewProfissao.setText(u.getProfissao());

    //Função onclick

    convertView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(c, u.getNome(), Toast.LENGTH_SHORT).show();
        }
    });



    return convertView;
 }
}

2 answers

4


The field saved is declared to be of the type Boolean.

Unlike the primitive type Boolean(b lower case), which is automatically initialized with the value false, the guy Boolean(Capital B) is null, if not initialized or instantiated.

The reason for the error is this: you are accessing a method(booleanValue()), class Boolean, in an object which is null.

From what I see in the code, nothing indicates that you need to use the class instead of the primitive type.

Therefore amend the declaration of saved of

Boolean saved;

for

boolean saved;

I also see no reason to give the error you indicate.

That error would be thrown if you used saved, before initializing it, in such situations:

if(saved){
    ...
    ...
}

or

boolean qualquerCoisa = saved;

I can’t find any case of these (or other) in your code , I just see initializations.

  • Well, from what I understand your answer only detailed my answer which already solved perhaps, I say perhaps, our friend Matheus. From what I noticed after some tests, his statement "...it needs to be instantiated before it can be used." is not true. I did it. a question to clarify a little more about the difference.

  • @seamusd. What is the problem if I give a more detailed answer? I say you must instantiate it because I speak in class in generic terms, Boolean is a particular case in which it can be done as you said, in case that should have explained to the AP and not start the answer by "Try to put ..." . On the other hand the way you speak is only possible from java 1.5, this is called autoboxing.

  • @seamusd I edited the answer. You have some reason, in the way it was could create some confusion.

  • 1

    Now yes you also have some reason, I’ll even give you a +1. Abs.

1

Try to put a value default for your variable saved:

private Boolean saved = true;

Browser other questions tagged

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