如何从Firebase android获取所有子列表

时间:2015-10-01 11:31:42

标签: android firebase firebase-realtime-database groupchat

我想在Android中使用Firebase中的所有子列表。

我已经实现了这段代码,但它无效。

mFirebaseRef = new Firebase(FIREBASE_URL);

mFirebaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> td = (ArrayList<String>) dataSnapshot.getValue();
        //notifyDataSetChanged();
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

18 个答案:

答案 0 :(得分:87)

我希望下面的代码可以运行

Firebase ref = new Firebase(FIREBASE_URL);

  ref.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
          Log.e("Count " ,""+snapshot.getChildrenCount());
          for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            <YourClass> post = postSnapshot.getValue(<YourClass>.class);
            Log.e("Get Data", post.<YourMethod>());
          }
      }
      @Override
      public void onCancelled(FirebaseError firebaseError) {
          Log.e("The read failed: " ,firebaseError.getMessage());
      }
  });

答案 1 :(得分:32)

Firebase以此格式存储一系列值:

"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1"
"-K-Y_RqDV_zbNLPJYnOA": "Value 2"
"-K-Y_SBoKvx6gAabUPDK": "Value 3"

如果你拥有它们,那么你的错误类型就是错误的。上述结构表示为Map,而不是List

mFirebaseRef = new Firebase(FIREBASE_URL);

mFirebaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

        List<Object> values = td.values();

        //notifyDataSetChanged();
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

答案 2 :(得分:22)

FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
 DatabaseReference databaseReference =    mFirebaseDatabase.getReference(FIREBASE_URL);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                    Log.v(TAG,""+ childDataSnapshot.getKey()); //displays the key for the node
                    Log.v(TAG,""+ childDataSnapshot.child(--ENTER THE KEY NAME eg. firstname or email etc.--).getValue());   //gives the value for given keyname
                }
            }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

希望它有所帮助!

答案 3 :(得分:11)

正如Frank所说 Firebase 以[{1}}格式存储值序列 这是地图结构

从此序列中获取列表

  1. 使用字符串 HashMap 和您的对象初始化 GenericTypeIndicator
  2. DataSnapShot 的值作为 GenericTypeIndicator 添加到地图
  3. 使用 HashMap 值初始化 ArrayList
  4. "key": "Value"

    对我来说很好,希望它有所帮助。

答案 4 :(得分:10)

我做了类似的事情:

Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {

@Override
public void onDataChange(DataSnapshot snapshot) {
    Map<String, Object> objectMap = (HashMap<String, Object>)    
             dataSnapshot.getValue();
    List<Match> = new ArrayList<Match>();
    for (Object obj : objectMap.values()) {
        if (obj instanceof Map) {
            Map<String, Object> mapObj = (Map<String, Object>) obj;
            Match match = new Match();
            match.setSport((String) mapObj.get(Constants.SPORT));
            match.setPlayingWith((String) mapObj.get(Constants.PLAYER));
            list.add(match);
        }
    }
  }
  @Override
  public void onCancelled(FirebaseError firebaseError) {

  }
});

答案 5 :(得分:5)

在我的情况下,只有给定解决方案才能正常工作。

Firebase ArrayList结构的屏幕截图:

enter image description here

如何从 DataSnapshot Firebase 获取整个列表

GenericTypeIndicator<Map<String, List<Education>>> genericTypeIndicator = new GenericTypeIndicator<Map<String, List<Education>>>() {};
Map<String, List<Education>> hashMap = dataSnapshot.getValue(genericTypeIndicator);

for (Map.Entry<String,List<Education>> entry : hashMap.entrySet()) {
      List<Education> educations = entry.getValue();
        for (Education education: educations){
             Log.i(TAG, education.Degree);
         }
}

Education.java:(模型类)。

public class Education implements Serializable{

    public String Degree;
    public String Result;
}

希望这样可以。

答案 6 :(得分:4)

如果您使用Kotlin,那么下一个是很好的解决方案:

myRef.addListenerForSingleValueEvent(object : ValueEventListener {
  override fun onDataChange(dataSnapshot: DataSnapshot) {
      val list = dataSnapshot.children.map { it.getValue(YourClass::class.java)!! }
      Log.d("TAG", "Value is: $list")
}

答案 7 :(得分:4)

保存和重播数据 - 来自Firebase (不推荐使用版本2.4.2)

Firebase fb_parent = new Firebase("YOUR-FIREBASE-URL/");
Firebase fb_to_read = fb_parent.child("students/names");
Firebase fb_put_child = fb_to_read.push(); // REMEMBER THIS FOR PUSH METHOD

//INSERT DATA TO STUDENT - NAMES  I Use Push Method
fb_put_child.setValue("Zacharia"); //OR fb_put_child.setValue(YOUR MODEL) 
fb_put_child.setValue("Joseph"); //OR fb_put_child.setValue(YOUR MODEL) 
fb_put_child.setValue("bla blaaa"); //OR fb_put_child.setValue(YOUR MODEL) 

//GET DATA FROM FIREBASE INTO ARRAYLIST
fb_to_read.addValuesEventListener....{
    public void onDataChange(DataSnapshot result){
        List<String> lst = new ArrayList<String>(); // Result will be holded Here
        for(DataSnapshot dsp : result.getChildren()){
            lst.add(String.valueOf(dsp.getKey())); //add result into array list
        }
        //NOW YOU HAVE ARRAYLIST WHICH HOLD RESULTS




for(String data:lst){ 
         Toast.make(context,data,Toast.LONG_LENGTH).show; 
       }
    }
}

答案 8 :(得分:3)

魅力十足

final DatabaseReference senderDb = FirebaseDatabase.getInstance().getReference(Constant.NODE_MESSAGE).child(myId + "_" + otherId);

    senderDb.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                DatabaseReference objRef = senderDb.child( childDataSnapshot.getKey());
                Map<String,Object> taskMap = new HashMap<String,Object>();
                taskMap.put("is_read", "1");
                objRef.updateChildren(taskMap); //should I use setValue()...?
                Log.v("Testing",""+ childDataSnapshot.getKey()); //displays the key for the node
            }

            //notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

答案 9 :(得分:2)

**Add value event method**

    @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
           for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
               User user = postSnapshot.getValue(User.class);
               list.add(user);
           }
           for (int i=0;i<list.size();i++)
           {
               Log.e("Name",list.get(i).getname());
               Log.e("Phone",list.get(i).getphone());

           }
       }
       @Override
       public void onCancelled(FirebaseError firebaseError) {
       Log.e("error",firebaseError.getMessage());
       }
   });

类模型

班级用户{

String name;

String phone;

public String getname() {
    return name;
}

public void setname(String name) {
    this.name = name;
}


public String getphone() {
    return phone;
}

public void setphone(String phone) {
    this.phone = phone;
}

}

列表绑定

List<User> list= new ArrayList <>();

为您服务

答案 10 :(得分:0)

mDatabase.child("token").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
              for (DataSnapshot snapshot:dataSnapshot.getChildren())
              {
                 String key= snapshot.getKey();
                 String value=snapshot.getValue().toString();
              }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(ListUser.this,databaseError.toString(),Toast.LENGTH_SHORT).show();
            }
        });

仅限工作如果孩子没有SubChild

enter image description here

答案 11 :(得分:0)

您需要编写自定义反序列化器,然后循环它并获取hasmap的值。

自定义反序列化器: -

public class UserDetailsDeserializer implements JsonDeserializer<AllUserDetailsKeyModel> {
  /*
    bebebejunskjd:{
      "email": "akhilbv1@gmail.com",
          "mobileNum": "12345678",
          "password": "1234567",
          "username": "akhil"}*/
  @Override public AllUserDetailsKeyModel deserialize(JsonElement json, Type typeOfT,
      JsonDeserializationContext context) throws JsonParseException {

    final JsonObject jsonObject = json.getAsJsonObject();

    Gson gson = new Gson();

    Type AllUserDetailsResponseModel =
        new TypeToken<HashMap<String, AllUserDetailsResponseModel>>(){}.getType();

    HashMap<String, AllUserDetailsResponseModel> user =
        gson.fromJson(jsonObject, AllUserDetailsResponseModel);
    AllUserDetailsKeyModel result = new AllUserDetailsKeyModel();
    result.setResult(user);
    return result;
  }


}

评论中的代码是我的对象模型,你应该用模型类替换AllUserDetailsKeyModel并将其添加到其他客户端,如下所示: -

private Converter.Factory createGsonConverter() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AllUserDetailsKeyModel.class, new UserDetailsDeserializer());
    Gson gson = gsonBuilder.create();
    return GsonConverterFactory.create(gson);
  }

这是自定义Convertor for Retrofit。

在onResponse中,你只需使用hasmaps循环并按键获取值,我的模型类如下所示: -

public class AllUserDetailsKeyModel {

  private Map<String, AllUserDetailsResponseModel> result;

  public Map<String, AllUserDetailsResponseModel> getResult() {
    return result;
  }

  public void setResult(Map<String, AllUserDetailsResponseModel> result) {
    this.result = result;
  }

}

可能你需要给出一个Type T,其中T是你的数据类型,我的模型只包含一个hashmap以及getter和setter。

最后将自定义转换器设置为如下所示进行改造: - .addConverterFactory(createGsonConverter())

如果您需要更多说明,请告诉我。

答案 12 :(得分:0)

使用GenericTypeIndicator从Firebase ArrayList结构化数据库获取子节点列表

   //Start of Code
   Firebase ref = new Firebase(FIREBASE_URL);
   ref.addValueEventListener(new ValueEventListener(){
      @Override
      public void onDataChange(DataSnapshot snapshot){
         GenericTypeIndicator<List<YourClassName>> t = new GenericTypeIndicator<List<YourClassName>>{};
         List<YourClassName> messages = snapshot.getValue(t);
         Log.d("Get Data Size", messages.size());
          }
      }
      @Override
      public void onCancelled(FirebaseError firebaseError){
          Log.e("The read failed: ",firebaseError.getMessage());
      }
   });

答案 13 :(得分:0)

您的问题是为什么您的代码不起作用。

您的代码:

Firebase ref = new Firebase(FIREBASE_URL);

  ref.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
          Log.e("Count " ,""+snapshot.getChildrenCount());
          for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            <YourClass> post = postSnapshot.getValue(<YourClass>.class);
            Log.e("Get Data", post.<YourMethod>());
          }
      }
      @Override
      public void onCancelled(FirebaseError firebaseError) {
          Log.e("The read failed: " ,firebaseError.getMessage());
      }
  })

您错过了最简单的事情:getChildren()

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference reference = FirebaseAuth.getInstance().getReference("Donald Trump");

reference.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {

            int count = (int) dataSnapshot.getChildrenCount(); // retrieve number of childrens under Donald Trump

            String[] hairColors = new String[count];

            index = 0;
            for (DataSnapshot datas : dataSnapshot.getChildren()){

                hairColors[index] = datas.getValue(String.class);

            }
            index ++

            for (int i = 0; i < count; i++)
            Toast(MainActivity.this, "hairColors : " + hairColors[i], toast.LENGTH_SHORT).show();

            }

    }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

答案 14 :(得分:0)

ArrayList<String> keyList = new ArrayList<String>();
mKeyRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                String temp = childDataSnapshot.getKey();
                keyList.add(temp);
                i = keyList.size();

            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });

此代码可以很好地将所有firebase键添加到arraylist中,您可以使用firebase值以及其他静态值来完成此操作。

答案 15 :(得分:0)

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference mMainMenuRef = mRootRef.child("tut_master");//main
        DatabaseReference mSubMenuRef = mMainMenuRef.child("english");//sub
        List<Tutorial>   tutorialNames=new ArrayList<>();
        mSubMenuRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    long id = ds.child("id").getValue(Long.class);
                    String name = ds.child("name").getValue(String.class);

                    Tutorial tut = new Tutorial();
                    tut.setTutId(id+"");
                    tut.setTutName(name);
                    tutList.add(tut);

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }


        });

答案 16 :(得分:0)

 private FirebaseDatabase firebaseDatabase=  FirebaseDatabase.getInstance();
    private DatabaseReference databaseReference=  firebaseDatabase.getReference();
    private DatabaseReference mChildReference= databaseReference.child("data");

  mChildReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    User commandObject = ds.getValue(User.class);
                    Log.d("TAG", commandObject.getMsg());
                }
                Toast.makeText(MainActivity.this,dataSnapshot.toString(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

这将为您提供帮助,您只需创建一个包含String msg的模型类即可。

答案 17 :(得分:0)

使用Gson是我最喜欢的解决方案。

mFirebaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Type StringListType = new TypeToken<List<String>>(){}.getType();
        List<String> td = new Gson().fromJson(dataSnapshot.getValue(), StringListType);
    }
});

如果您认为获取TypeToken的代码不直观。您可以编写一个类来包含所需的所有类型。因此,下次您可以快速获取这些类型。

class TypeTokens{
    static public final Type StringListType = new TypeToken<List<String>>(){}.getType();
    static public final Type StringMapType = new TypeToken<Map<String, String>>(){}.getType();
    static public final Type LongMapType = new TypeToken<Map<String, Long>>(){}.getType();
    static public final Type DateMapType = new TypeToken<Map<String, Date>>(){}.getType();
}