0

I'm creating an application which will hold a number of users and their clients in a firebase database. I have users with relevant clients and I want to display the client list for the current user, but when I prompt the displaying of the clients, the application crashes. I don't know if it's due to incorrect code or the layout of the clients.

The this point

 userClients.addListenerForSingleValueEvent(new ValueEventListener() {

the program does not like the ValueEventListener.

Any help would be appreciated.

public class ClientList extends AppCompatActivity {

String userId;

FirebaseAuth mAuth;
FirebaseUser firebaseUser;
DatabaseReference databaseRef;
String clientAddress;
String clientPhone;
ListView myClientList;
List<String> clientArrayList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client_list);

    mAuth = FirebaseAuth.getInstance();

    myClientList = (ListView) findViewById(R.id.clientList);
    clientArrayList = new ArrayList<>();

    getClientList();

}

public void getClientList(){

    databaseRef = FirebaseDatabase.getInstance().getReference();
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if (firebaseUser!=null){
        userId = firebaseUser.getUid();
    }

    Query userClients = databaseRef.child("users").child(userId);


    userClients.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Iterate through the friends JSON tree (for current user)
            for (DataSnapshot myDatabase : dataSnapshot.getChildren()) {
                clientAddress = myDatabase.child("Address").getValue(String.class);
                clientPhone = myDatabase.child("phone").getValue(String.class);

                clientArrayList.add( clientAddress + ", " + clientPhone );
            }
            createListView();

            if (clientArrayList.isEmpty()) {
                Toast.makeText(ClientList.this, "No Clients", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

}



public void createListView() {

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(Integer.parseInt(userId)));
    myClientList.setAdapter(adapter);

}




ClientList}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
                                                                                   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: Can't pass null for argument 'pathString' in child()
KENdi
  • 7,576
  • 2
  • 16
  • 31
Rac Egan
  • 1
  • 1

3 Answers3

0

When there is no signed-in user, firebaseUser will be null and userId will not be set, leaving it with its null default value. That will result in child() being called with a null argument, which it the cause of the exception:

public void getClientList(){

    databaseRef = FirebaseDatabase.getInstance().getReference();
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if (firebaseUser!=null){
        userId = firebaseUser.getUid();
    }

    Query userClients = databaseRef.child("users").child(userId); // userId == null here
    ...
}
Bob Snyder
  • 37,759
  • 6
  • 111
  • 158
  • i have created a user, and i have signed in successfully with that user. So why is the userId == null? – Rac Egan Aug 30 '17 at 19:27
  • @RacEgan: Add some debug logging to confirm that `firebaseUser != null`. – Bob Snyder Aug 30 '17 at 19:36
  • Verification failed on class com.google.android.gms.internal.zzatp in /data/app/com.example.rachel.finalyearproject-2/split_lib_dependencies_apk.apk:classes15.dex because: Verifier rejected class com.google.android.gms.internal.zzatp due to bad method com.google.android.gms.internal.zzaso com.google.android.gms.internal.zzatp.zzJg() 08-30 20:05:50.012 7535-7535/com.example.rachel.finalyearproject A/FirebaseApp: Firebase API initialization failure.com.google.android.gms.internal.zzatp.zzJg() Firebase API initialization failure. – Rac Egan Aug 30 '17 at 20:10
  • @RacEgan: You can try doing a Clean and rebuilding, although that may not help. You probably need to post your app module build.gradle so we can see what libraries and versions you are building with. – Bob Snyder Aug 30 '17 at 20:24
  • Thanks Bob. I using 10.0.1 libraries for core, database,, crash, auth, play-service-auth, and messaging........appcompat-v7 and design= 25.3.1. and firebase-client-android = 2.5.2. they are all compatible with each other. – Rac Egan Aug 30 '17 at 20:47
  • @RacEgan: Not good to mix the legacy SDK, `firebase-client-android`, with the "new" , 10.0.1, SDK (current version is 11.2.0). I suspect that is the source of the errors. Is there a reason you have not completely migrated to the new SDK? – Bob Snyder Aug 30 '17 at 21:10
0

Try this:

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    DatabaseReference userRef = database.getReference("users").child(user.getUid());//DatabaseReference, no Query

And tell if it works

Razvan
  • 292
  • 2
  • 3
  • 15
  • No problem. Are you sure you write the code correctly for authentication process? Check my answer here https://stackoverflow.com/questions/45967649/firebase-authentication-error-in-android/45967699#45967699 – Razvan Aug 30 '17 at 20:26
0

This is because user might not have signed in and hence userId is null. You can do the following to resolve the same.

public class ClientList extends AppCompatActivity {

    String userId;

    FirebaseAuth mAuth;
    FirebaseUser firebaseUser;
    DatabaseReference databaseRef;
    String clientAddress;
    String clientPhone;
    ListView myClientList;
    List<String> clientArrayList;

    // 1. Add AuthStateListener
    private FirebaseAuth.AuthStateListener mAuthListener;

    // 3.add and remove AuthStateListener on Activity's onStart and onStop respectively
    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mAuth.removeAuthStateListener(mAuthListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_list);


        mAuth = FirebaseAuth.getInstance();

        // 2. Init the AuthStateListener
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                /*
                    Everytime a user is signed in/out, this will be called. 
                    (Including when the activity launches)
                */

                if (firebaseAuth.getCurrentUser() != null) {
                   // User signed in, now get client-list
                    getClientList();
                } else {
                  /* No user signed in, First sign in. After having signed in, again this method will be called (since the auth-state has changed). Then the if-case runs and getClientList() is called
                  */
                    mAuth.signInWithEmailAndPassword("user_email", "user_password");
                }
            }
        };
    }
Sumit Jha
  • 2,095
  • 2
  • 21
  • 36