0

I have a problem with my code. The error is:

FATAL EXCEPTION: main
                                                        Process: bike.ellos.ellos, PID: 22835
                                                              java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.firebase.auth.FirebaseAuth$AuthStateListener.onAuthStateChanged(com.google.firebase.auth.FirebaseAuth)' on a null object reference
                                                                  at com.google.firebase.auth.FirebaseAuth$2.run(Unknown Source)
                                                                  at android.os.Handler.handleCallback(Handler.java:739)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                  at android.os.Looper.loop(Looper.java:148)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

The SplashScreen.class code is:

public class SplashScreen extends Activity {

private int counter = 0;
private Integer pontos;
private String userId;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;

FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);
    mAuth = FirebaseAuth.getInstance();
    IniciaSplash();
}
//FUNÇÃO QUE CONTA OS SEGUNDO E MUDA A TELA
public void IniciaSplash(){
    new Thread(new Runnable() {

        @Override
        public void run() {
            counter++;
            try{
                while (counter==1 || counter<3)//TEMPO DE ESPERA DO CONTADOR "5"
                {
                    Thread.sleep(1000);
                    counter++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (counter==3){
                //ACRESCE UM NO CONTADOR PARA NÃO VIRAR UM LOOP INFINITO
                counter++;
                UserCheck();
            }
        }

    }).start();
}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

private void UserCheck(){
    ///Checa se o usuário ja esta logado
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            //Se o usuário já estiver logado
            if(firebaseAuth.getCurrentUser() == null){

                startActivity(new Intent(SplashScreen.this,Register.class));
                SplashScreen.this.finish();

            }else{
                userDataLoged();
                getRealtimeScore();
            }
        }
    };
}

private void userDataLoged(){
    userId = firebaseUser.getUid();
}

//Pega os pontos no Firebase Realtime
private void getRealtimeScore(){
    // Verifica os dados no Firebase Realtime
    mFirebaseDatabase.child(userId).child("score").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //verifica se ta cadastrado corretamente
            if (dataSnapshot != null){
                //Atribui o valor do "score" aos pontos
                pontos = dataSnapshot.getValue(Integer.class);

                //Se os pontos forem "NULL" é pq o usuário não registrou completamente(PersonalRegistration)
                if(pontos == null){
                    startActivity(new Intent(SplashScreen.this, PersonalRegistration.class));
                    SplashScreen.this.finish();
                    finish();
                    Toast.makeText(SplashScreen.this, "Finalize o cadastro" , Toast.LENGTH_LONG).show();
                }else {
                    startActivity(new Intent(SplashScreen.this, MainActivity.class));
                    SplashScreen.this.finish();
                    finish();
                }
            }else{
                mAuth.signOut();
            }
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Toast.makeText(SplashScreen.this, "onCancelled" , Toast.LENGTH_LONG).show();
        }
    });
}
}

The application doesn't open. So I run the application, it crashes. I've tried a lot of things, but I have not got a solution for that. Would anyone have any solution for this?

AL.
  • 36,815
  • 10
  • 142
  • 281
Luiz
  • 13
  • 3
  • `mAuthListener` is null in the moment you call `mAuth.addAuthStateListener(mAuthListener);`. Initialize it earlier. You'll have to change logic of the code too. Think twice, do you really need counter and `Thread.sleep()`? – Sergey Glotov Mar 02 '17 at 01:58
  • Offtopic: don't write methods names starting with capital letter please – Sergey Glotov Mar 02 '17 at 01:59
  • @SergeyGlotov If I put the `mAuth.addAuthStateListener (mAuthListener);` On `onCreat`, will the problem probably be solved? I did not fully enclose the reason for being null if I put it `onStart ()`. The reason for `Thread.sleep ();` Is a minimum amount of time on SplashScreen. – Luiz Mar 02 '17 at 23:07
  • @SergeyGlotov And I changed the capital letter, tanks! – Luiz Mar 02 '17 at 23:09
  • @SergeyGlotov I just found out that the problem is in `iniciaSplash ()`, the class that does the `Thread.sleep ();` . Would you have any solution to tell me? – Luiz Mar 02 '17 at 23:22
  • What problem do you see in `iniciaSplash()`? – Sergey Glotov Mar 03 '17 at 07:05

0 Answers0