1

Desenvolvi uma aplicação estava cadastrando e tudo mais, mas na hora que implementei a função para exibir os dados em um LogCat, a minha aplicação parou até mesmo de iniciar a Activity. Alguém jé teve esse erro? Agradeço a ajuda desde já.

Apresenta o seguinte erro

FATAL EXCEPTION: main Process: com.example.matheus.kypy, PID: 9373 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matheus.kypy/com.example.matheus.kypy.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.FirebaseDatabase.getReference(java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.FirebaseDatabase.getReference(java.lang.String)' on a null object reference at com.example.matheus.kypy.Main.onCreate(Main.java:54) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

 

Classes do projeto:

public class Main extends AppCompatActivity {
    private EditText etNome, etData, etRg, etCpf, etEndereco, etDoenca, etProfissao;
    private TextView textViewInfo;
    private Button buttonCadastro, buttonListar,buttonVoltar;
    private FirebaseDatabase BD;
    private DatabaseReference bdR,myRef;//bdR = Banco de Dados Referencia
    private Usuarios novoUsuario;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 //Parte do Layout {
    //Botões
    buttonCadastro = (Button) findViewById(R.id.buttonCadastro);
    buttonListar = (Button) findViewById(R.id.buttonListar);
    buttonVoltar = (Button) findViewById(R.id.buttonVoltar);
    //EditTexts
    etNome = (EditText) findViewById(R.id.etNome);
    etData = (EditText) findViewById(R.id.etData);
    etRg = (EditText) findViewById(R.id.etRg);
    etCpf = (EditText) findViewById(R.id.etCpf);
    etEndereco = (EditText) findViewById(R.id.etEndereco);
    etDoenca = (EditText) findViewById(R.id.etDoenca);
    etProfissao = (EditText) findViewById(R.id.etProfissao);
    //TextViews
    textViewInfo = (TextView) findViewById(R.id.textViewInfo);
 //Parte do Layout }
    //-----------------------------------------------------------
    //BD
    bdR = FirebaseDatabase.getInstance().getReference();
    myRef = BD.getReference("-KSXUo45LKXpWMOX-BfY");

    //-----------------------------------------------------------

    buttonCadastro.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            novoUsuario = new Usuarios(
                    etNome.getText().toString(),
                    etData.getText().toString(),
                    etRg.getText().toString(),
                    etCpf.getText().toString(),
                    etEndereco.getText().toString(),
                    etDoenca.getText().toString(),
                    etProfissao.getText().toString());

            bdR.push().setValue(novoUsuario);

        }

    });

    buttonListar.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View v) {
          myRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                 Usuarios u = dataSnapshot.getValue(Usuarios.class);
                     Log.e("Meu: Nome", u.getNome());
                     Log.e("Meu: Data", u.getData());
                     Log.e("Meu: RG", u.getRg());
                     Log.e("Meu: CPF", u.getCpf());
                     Log.e("Meu: Endereço", u.getEndereco());
                     Log.e("Meu: Doença", u.getDoenca());
                     Log.e("Meu: Profissão", u.getProfissao());

                 }


                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    });
}


public void abreInfo(View view){
    Intent intent = new Intent(this,Usuarios.class);
   startActivity(intent);
    setContentView(R.layout.activity_info);
}

}

Usuario dados:

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 Usuarios(String Nome, String Data, String Rg, String Cpf, String Endereco, String Doenca, String Profissao) {
    this.Nome = Nome;
    this.Data = Data;
    this.Rg = Rg;
    this.Cpf = Cpf;
    this.Endereco = Endereco;
    this.Doenca = Doenca;
    this.Profissao = Profissao;
}
public Usuarios() {

}

1 Resposta 1

1

Isso acontece porque você está acessando a variável BD antes de ela ser inicializada nesta linha:

myRef = BD.getReference("-KSXUo45LKXpWMOX-BfY");

Inicialize a variável antes de usá-la:

    //BD
    BD = FirebaseDatabase.getInstance();
    bdR = BD.getReference();
    myRef = BD.getReference("-KSXUo45LKXpWMOX-BfY");

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .