如何从Android中的firebase返回值?

时间:2018-01-29 12:33:51

标签: java android multithreading firebase firebase-realtime-database

class Group < ApplicationRecord 
  has_many :group_users
  has_many :users, through: :group_users

  has_many :group_user_roles
  has_many :roles, through: :group_user_roles
end

class User < ApplicationRecord 
  has_many :group_users
  has_many :groups, through: :group_users

  has_many :group_user_roles
  has_many :roles, through: :group_user_roles
end

class GroupUser < ApplicationRecord
    belongs_to :group
    belongs_to :user
end

class Role < ApplicationRecord
end

class GroupUserRole < ApplicationRecord
  belongs_to :user
  belongs_to :group
  belongs_to :role
end

我可以使用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) { } }); } 方法获取数据,但我无法找到在全局范围内捕获foodItem对象的方法。我需要返回foodItem对象。我该怎么办?

2 个答案:

答案 0 :(得分:1)

定义界面:

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()方法的调用者可以传递一个侦听器,该侦听器将在检索食物或发生错误时被调用。

答案 1 :(得分:0)

对addValueEventListener的调用是异步的,因此您可以在onDataChange()方法中收到数据时更新UI。

如果要将其存储在全局变量中,只需在方法外声明它并在回调上更新:

private FoodItem foodItem;

public void getFoodItem(String foodNum){
    // ...
    dbReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            foodItem = dataSnapshot.getValue(FoodItem.class);
            // now update the UI
        }
        // ...
}