如何从Firebase实时数据库读取和返回数据?

时间:2018-10-02 02:50:22

标签: android firebase-realtime-database

我试图从firebase db读取数据并将值返回给另一个方法,为此我添加了interface并将其用作回调函数并试图等待直到数据填满。但是它仍然给出了空指针异常。

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>..........................");
        }
    });

}

这是错误:

enter image description here

这是数据库

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您解析堆栈跟踪,则会收到由println needs a message触发的错误消息Log.d。在您共享的代码中,有两条语句可以触发该消息:

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

还有

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

databaseError.getMessage()似乎什么也不返回,因此card.getAccountId()几乎什么也不返回或null的可能性很小。一个简单的解决方案是检查:

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

空指针异常非常常见,知道如何解决它们是一项很好的技能。我建议学习:What is a NullPointerException, and how do I fix it?