简体   繁体   中英

How to receive specific information from Firebase Realtime db in Android?

I'm creating a loyalty application with Android Studio and Firebase Real time Database.

Each user registered with the application will have a unique QR Code assigned to their account.

When the user registers in the application, there information is stored in the database and will be called back into the application. The database scheme can be seen below.

在此处输入图片说明

I am trying to call back the user's email address from firebase using event listner :

 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String email = dataSnapshot.child("email").getValue().toString();

            Toast.makeText(HomeScreen.this, email
                    , Toast.LENGTH_SHORT).show();


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());

        }
    });

Declared instances:

 FirebaseDatabase database = FirebaseDatabase.getInstance();
 databaseReference = database.getReference("Customers");
 firebaseAuth = FirebaseAuth.getInstance();
 firebaseUser = firebaseAuth.getCurrentUser();

When running I keep getting null pointer exception.

2019-12-04 12:45:47.714 25381-25381/com.example.alicearmstrong.coffeysloyalty E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.alicearmstrong.coffeysloyalty, PID: 25381 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at com.example.alicearmstrong.coffeysloyalty.HomeScreen$1.onDataChange(HomeScreen.java:71) at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75) at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63) at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Na tive Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Anyone able to help to resolve?

You need to iterate inside the random id to be able to retrieve the email field:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  for(DataSnapshot ds : dataSnapshot.getChildren()){
    String email = ds.child("email").getValue().toString();

    Toast.makeText(HomeScreen.this, email
            , Toast.LENGTH_SHORT).show();
    }
}

No, you're doing it wrong.

Judging by your database schema, your databaseReference.addValueEventListener(...) call gives you access to a datasnapshot which is basically a list of all the uIDs.

Therefore, when you perform database.child("email").getValue().toString() , it is bound to be null because the datasnapshot only contains uId objects and no direct email property. It'd always result in a NullPointerException.

Solution:

Since you are trying to retrieve the email of a specific user, simply add the user's id into your databaseReference object, that way, you'd be able to get the email directly with the rest of your approach.

Here's an illustration:

// this variable represents the uId of specific user you want to retrieve the email of
String userId = "INSERT_USERID_HERE";

// add userId above as a child to your databaseReference object
databaseReference = database.getReference("Customers").child("userId");

// valueEventListener call
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String email = dataSnapshot.child("email").getValue().toString();
        Toast.makeText(HomeScreen.this, email, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM