This question already has answers here:
Setting Singleton property value in Firebase Listener
                                
                                    (3个答案)
                                
                        
                2年前关闭。
            
        

public  void getFoodItem( String foodNum) {

    dbReference=firebaseDatabase.getReference("Food"+foodNum);

    dbReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            FoodItem foodItem = dataSnapshot.getValue(FoodItem.class);
            Log.d("h", "Gotdata" + foodItem.getImage());
           //Data can be taken from here, assigning to a global variable results null

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}


我可以使用onDataChange()方法获取数据,但无法找到在全局范围内捕获foodItem对象的方法。我需要返回foodItem对象。我该怎么做?

最佳答案

定义一个接口:

interface FoodListener {

    void onFoodReceived(FoodItem foodItem);
    void onError(Throwable error);
}


然后修改您的方法:

public  void getFoodItem(String foodNum, final FoodListener listener) {

    dbReference=firebaseDatabase.getReference("Food"+foodNum);

    dbReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            FoodItem foodItem = dataSnapshot.getValue(FoodItem.class);
            Log.d("h", "Gotdata" + foodItem.getImage());

            listener.onFoodReceived(foodItem);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            listener.onError(databaseError.toException());
        }
    });
}


现在,getFoodItem()方法的调用者可以传递一个侦听器,该侦听器将在检索食物或发生错误时被调用。

09-27 05:32