如何从包含唯一键的firebase实时数据库中获取字符串

时间:2016-06-20 09:54:20

标签: java android firebase firebase-realtime-database

我想从中获取一个字符串:

this

,但它有一个唯一的关键父级。我如何从db获取字符串?我试过了:

    firebaseAuth = FirebaseAuth.getInstance();
    fUID =firebaseAuth.getCurrentUser().getUid();
    itemsUrl ="https://nextweaverproject.firebaseio.com/users/" + fUID  ;
    mDatabase = FirebaseDatabase.getInstance();
    final DatabaseReference myRef = mDatabase.getReferenceFromUrl(itemsUrl);
    myRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Map<String, Object> td = (HashMap<String,Object>)    dataSnapshot.getValue();
                List<Object> values = new ArrayList<Object>(td.values());

                    strFb = new ArrayList<String>();
                    strFb.add(values.get(0).toString());


               // strFb.add(urlLong);
                Log.v("test","   "  +  strFb.get(strFb.size()-1));

        }

但它返回db中的所有对象。

2 个答案:

答案 0 :(得分:2)

您可以使用child从数据库树中获取数据:

myRef.child("Scenes").child("Scene").("******").
(*****).addChildEventListener(new ChildEventListener() {

这样你应该链接你的领域。

您也可以使用addValueEventListener, addListenerForSingleValueEvent。 你可以在这里阅读它们:     https://firebase.google.com/docs/database/android/retrieve-data

答案 1 :(得分:2)

谢谢大家。我找到了我的解决方案:

myRef.child("Scenes").child("Scene").addValueEventListener(new ValueEventListener() {
               @Override
               public void onDataChange(DataSnapshot dataSnapshot) {
                   for (DataSnapshot children : dataSnapshot.getChildren()) {
                       for (DataSnapshot child : children.getChildren()) {
                           //Log.v("key1","   " + child.getKey());
                           if(child.getKey().equals("Thumb")){
                               for (DataSnapshot child2 : child.getChildren()) {
                                   //Log.v("key2","   " + child2.getValue(String.class));
                                   for (DataSnapshot child3 : child2.getChildren()) {
                                       //Log.v("key3","   " + child3.getKey());
                                       if(child3.getKey().equals("LongUrl")){
                                           Log.v("key4","   " + child3.getValue(String.class));
                                            thumbUrl.add(child3.getValue().toString());
                                       }
                                   }
                               }
                           }
                       }

                       Log.v("keyResult","   " + thumbUrl);
                      // Log.v("key2","   " + thumbUrl);
                   }
               }

               @Override
               public void onCancelled(DatabaseError databaseError) {

               }
           });

结果在此处:Result