-2

I tried to read data from firebase db and return values to another method.To do that I added interface and use it as a callback function and tried to wait until data filled. But it still give the null pointer exception.

private interface FirebaseCallback {
    void onCallBack(Card card);
}


// method to read travel Cards
public void readCard(final FirebaseCallback fb) {

    cardNo = (EditText)findViewById(R.id.editTextCardNo);

    ValueEventListener cardListner = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(dataSnapshot.exists()) {

                travelCard = dataSnapshot.getValue(Card.class);
                fb.onCallBack(travelCard);

            }

            else displayMessage(inValidTravelCard);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d("ERROR : ", databaseError.getMessage());
        }
    };

    String cn = cardNo.getText().toString();
    Query q = FirebaseDatabase.getInstance().getReference("Card").orderByChild("cardNumber").equalTo(cn).limitToFirst(1);
    q.addListenerForSingleValueEvent(cardListner);

}



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

                  System.out.println("fffffffffffffffffffffffffffffff    " +  " BEFORE>..........................");

            readCard(new FirebaseCallback() {
                @Override
                public void onCallBack(Card card) {
                    Log.d("card = ",card.getAccountId());
                }
            });

            System.out.println("fffffffffffffffffffffffffffffff    " +  " After>..........................");
        }
    });

}

Here's the ERROR :

enter image description here

Here's the database

enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
EMYLs
  • 27
  • 7

1 Answers1

1

If you parse the stack trace you get the error message you get is println needs a message, triggered from Log.d. In the code you shared, there are two statements that could trigger that message:

Log.d("ERROR : ", databaseError.getMessage());

And

Log.d("card = ",card.getAccountId());

It seems quite unlikely that databaseError.getMessage() returns nothing, so it's more likely that card.getAccountId() returns nothing or null. A simple solution is to check for that:

Log.d("card = ", card.getAccountId() != null ? card.getAccountId() : "No account ID found on card");

Null pointer exceptions are extremely common, and knowing how to troubleshoot them is a skill that will serve you well. I recommend studying: What is a NullPointerException, and how do I fix it?.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807