Java Code Examples for com.google.firebase.database.DataSnapshot#getChildren()

The following examples show how to use com.google.firebase.database.DataSnapshot#getChildren() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HomeActivity.java    From wmn-safety with MIT License 6 votes vote down vote up
public void getUserName(final String UID) {
    final StringBuffer buffer = new StringBuffer("");
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if (snapshot.getKey().equals("name")) {
                    buffer.append(snapshot.getValue());
                }
            }
            mFullName = buffer.toString();
            updateProfile();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
    mDatabaseReference.child("users").child(UID).addListenerForSingleValueEvent(eventListener);

}
 
Example 2
Source File: DumpFeedback.java    From white-label-event-app with Apache License 2.0 6 votes vote down vote up
private void writeSessionRow(final DataSnapshot session) throws IOException {
    final String session_id = session.getKey();
    for (final DataSnapshot session_user : session.getChildren()) {
        writer.write(session_id);
        final String user_id = session_user.getKey();
        writer.write('\t');
        writer.write(user_id);
        for (DataSnapshot rating : session_user.getChildren()) {
            writer.write('\t');
            final Object value = rating.getValue();
            if (value != null) {
                writer.write(value.toString());
            }
        }
        writer.write('\n');
    }
}
 
Example 3
Source File: MainAppPage.java    From NITKart with MIT License 6 votes vote down vote up
public static ArrayList<ShoppingItem> getAllItems(DataSnapshot dataSnapshot){

        ArrayList<ShoppingItem> items  = new ArrayList<ShoppingItem>();

        for (DataSnapshot item : dataSnapshot.getChildren()) {

            items.add(new ShoppingItem(
                    item.child("productID").getValue().toString(),
                    item.child("name").getValue().toString(),
                    item.child("type").getValue().toString(),
                    item.child("description").getValue().toString(),
                    Integer.valueOf(item.child("price").getValue().toString()),
                    Integer.valueOf(item.child("quantity").getValue().toString())
            ));

        }

        return items;
    }
 
Example 4
Source File: ResolverDataSnapshotList.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static List resolve(DataSnapshot dataSnapshot) {
    if (dataSnapshot.getValue() == null) {
        throw new IllegalStateException();
    }
    List result = new ArrayList<>();
    Iterable<DataSnapshot> dataSnapshots;
    if (ClassReflection.isAssignableFrom(Map.class, dataSnapshot.getValue().getClass())) {
        dataSnapshots = ((Map) dataSnapshot.getValue()).values();
    } else {
        dataSnapshots = dataSnapshot.getChildren();
    }
    for (Object o : dataSnapshots) {
        if (o instanceof DataSnapshot) {
            result.add(((DataSnapshot) o).getValue());
        } else {
            result.add(o);
        }
    }
    return result;
}
 
Example 5
Source File: ParseFirebaseData.java    From FChat with MIT License 6 votes vote down vote up
public List<ChatMessage> getMessagesForSingleUser(DataSnapshot dataSnapshot) {
    List<ChatMessage> chats = new ArrayList<>();
    String text = null, msgTime = null, senderId = null, senderName = null, senderPhoto = null,
        receiverId = null, receiverName = null, receiverPhoto = null;
    Boolean read = Boolean.TRUE;
    for (DataSnapshot data : dataSnapshot.getChildren()) {
        text = data.child(NODE_TEXT).getValue().toString();
        msgTime = data.child(NODE_TIMESTAMP).getValue().toString();
        senderId = data.child(NODE_SENDER_ID).getValue().toString();
        senderName = data.child(NODE_SENDER_NAME).getValue().toString();
        senderPhoto = data.child(NODE_SENDER_PHOTO).getValue().toString();
        receiverId = data.child(NODE_RECEIVER_ID).getValue().toString();
        receiverName = data.child(NODE_RECEIVER_NAME).getValue().toString();
        receiverPhoto = data.child(NODE_RECEIVER_PHOTO).getValue().toString();
        //Node isRead is added later, may be null
        read = data.child(NODE_IS_READ).getValue() == null ||
            Boolean.parseBoolean(data.child(NODE_IS_READ).getValue().toString());

        chats.add(
            new ChatMessage(text, msgTime, receiverId, receiverName, receiverPhoto, senderId,
                senderName, senderPhoto, read));
    }
    return chats;
}
 
Example 6
Source File: BasketFragment.java    From RestaurantApp with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        productBasket = new ProductBasket();
        productBasket.setPiece(snapshot.getValue(ProductBasket.class).getPiece());
        productBasket.setProductId(snapshot.getValue(ProductBasket.class).getProductId());
        productBaskets.add(productBasket);
    }

    try {
        Toast.makeText(getActivity(), productBaskets.size()+"", Toast.LENGTH_SHORT).show();
    }catch (Exception e){

    }

}
 
Example 7
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartAtWithTwoArguments()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  new WriteFuture(ref,
      MapBuilder.of(
          "Walker", MapBuilder.of("name", "Walker", "score", 20, ".priority", 20),
          "Michael", MapBuilder.of("name", "Michael", "score", 100, ".priority", 100)))
      .timedGet();

  DataSnapshot snap = TestHelpers.getSnap(ref.startAt(20, "Walker").limitToFirst(2));
  List<String> expected = ImmutableList.of("Walker", "Michael");
  int i = 0;
  for (DataSnapshot child : snap.getChildren()) {
    assertEquals(expected.get(i), child.getKey());
    i++;
  }
  assertEquals(2, i);
}
 
Example 8
Source File: NotificationChannel.java    From Shipr-Community-Android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    int local_count = 0;
    for (DataSnapshot message : dataSnapshot.getChildren()) {
        DeveloperMessage developerMessage = message.getValue(DeveloperMessage.class);
        local_count++;
        if (local_count > count) {
            count = local_count;
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("count", count);
            editor.apply();
            messages.add(developerMessage);
        }
    }
    if (messages.size() > 0) Notify();
}
 
Example 9
Source File: ParseFirebaseData.java    From FChat with MIT License 5 votes vote down vote up
public ArrayList<Friend> getAllUser(DataSnapshot dataSnapshot) {
    ArrayList<Friend> frnds = new ArrayList<>();
    String name = null, id = null, photo = null;
    for (DataSnapshot data : dataSnapshot.getChildren()) {
        name = data.child(NODE_NAME).getValue().toString();
        id = data.child(NODE_USER_ID).getValue().toString();
        photo = data.child(NODE_PHOTO).getValue().toString();

        if (!set.readSetting(Constants.PREF_MY_ID).equals(id)) {
            frnds.add(new Friend(id, name, photo));
        }
    }
    return frnds;
}
 
Example 10
Source File: MainAppPage.java    From NITKart with MIT License 5 votes vote down vote up
public static ArrayList<ShoppingItem> setUpList(DataSnapshot dataSnapshot) {

        ArrayList<ShoppingItem> items  = new ArrayList<ShoppingItem>();

        for (DataSnapshot snap : dataSnapshot.getChildren()){

            int itemPrice = -1, quantity = 0;

            try{
                itemPrice = Integer.valueOf(NumberFormat.getCurrencyInstance()
                        .parse(String.valueOf(snap.child("price").getValue()))
                        .toString());
            } catch (ParseException e){
                e.printStackTrace();
            }

            quantity = Integer.valueOf(snap.child("quantity").getValue().toString());
            items.add(new ShoppingItem(
                    snap.child("productID").getValue().toString(),
                    snap.child("title").getValue().toString(),
                    snap.child("type").getValue().toString(),
                    snap.child("description").getValue().toString(),
                    itemPrice,
                    quantity
            ));
        }

        return items;

    }
 
Example 11
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
private <T> List<T> extractList(DataSnapshot dataSnapshot, Class<T> itemClass) {
    Iterable<DataSnapshot> items = dataSnapshot.getChildren();
    List<T> result = new ArrayList<>();
    for (DataSnapshot item : items) {
        result.add((extract(item, itemClass)));
    }
    return result;
}
 
Example 12
Source File: DataSnapshotMapper.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@Override
public List<U> call(final DataSnapshot dataSnapshot) {
    List<U> items = new ArrayList<>();
    for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
        items.add(getDataSnapshotTypedValue(childSnapshot, clazz));
    }
    return items;
}
 
Example 13
Source File: DataSnapshotMapper.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@Override
public LinkedHashMap<String, U> call(final DataSnapshot dataSnapshot) {
    LinkedHashMap<String, U> items = new LinkedHashMap<>();
    for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
        items.put(childSnapshot.getKey(), getDataSnapshotTypedValue(childSnapshot, clazz));
    }
    return items;
}
 
Example 14
Source File: FirestackUtils.java    From react-native-firestack with MIT License 5 votes vote down vote up
public static WritableArray getChildKeys(DataSnapshot snapshot) {
  WritableArray childKeys = Arguments.createArray();

  if (snapshot.hasChildren()) {
    for (DataSnapshot child : snapshot.getChildren()) {
      childKeys.pushString(child.getKey());
    }
  }

  return childKeys;
}
 
Example 15
Source File: ParseFirebaseData.java    From FChat with MIT License 4 votes vote down vote up
public ArrayList<ChatMessage> getAllLastMessages(DataSnapshot dataSnapshot) {
    // TODO: 11/09/18 Return only last messages of every conversation current user is
    //  involved in
    ArrayList<ChatMessage> lastChats = new ArrayList<>();
    ArrayList<ChatMessage> tempMsgList;
    long lastTimeStamp;
    String text = null, msgTime = null, senderId = null, senderName = null, senderPhoto = null,
        receiverId = null, receiverName = null, receiverPhoto = null;
    Boolean read = Boolean.TRUE;
    for (DataSnapshot wholeChatData : dataSnapshot.getChildren()) {

        tempMsgList = new ArrayList<>();
        lastTimeStamp = 0;

        for (DataSnapshot data : wholeChatData.getChildren()) {
            msgTime = data.child(NODE_TIMESTAMP).getValue().toString();
            if (Long.parseLong(msgTime) > lastTimeStamp) {
                lastTimeStamp = Long.parseLong(msgTime);
            }
            text = data.child(NODE_TEXT).getValue().toString();
            senderId = data.child(NODE_SENDER_ID).getValue().toString();
            senderName = data.child(NODE_SENDER_NAME).getValue().toString();
            senderPhoto = data.child(NODE_SENDER_PHOTO).getValue().toString();
            receiverId = data.child(NODE_RECEIVER_ID).getValue().toString();
            receiverName = data.child(NODE_RECEIVER_NAME).getValue().toString();
            receiverPhoto = data.child(NODE_RECEIVER_PHOTO).getValue().toString();
            //Node isRead is added later, may be null
            read = data.child(NODE_IS_READ).getValue() == null ||
                Boolean.parseBoolean(data.child(NODE_IS_READ).getValue().toString());

            tempMsgList.add(
                new ChatMessage(text, msgTime, receiverId, receiverName, receiverPhoto,
                    senderId, senderName, senderPhoto, read));
        }

        for (ChatMessage oneTemp : tempMsgList) {
            if ((set.readSetting(Constants.PREF_MY_ID).equals(oneTemp.getReceiver().getId())) ||
                (set.readSetting("myid").equals(oneTemp.getSender().getId()))) {
                if (oneTemp.getTimestamp().equals(String.valueOf(lastTimeStamp))) {
                    lastChats.add(oneTemp);
                }
            }
        }
    }
    return lastChats;
}
 
Example 16
Source File: ParseFirebaseData.java    From FChat with MIT License 4 votes vote down vote up
public ArrayList<ChatMessage> getAllUnreadReceivedMessages(DataSnapshot dataSnapshot) {
    ArrayList<ChatMessage> lastChats = new ArrayList<>();
    ArrayList<ChatMessage> tempMsgList;
    long lastTimeStamp;
    String text, msgTime, senderId, senderName, senderPhoto, receiverId, receiverName,
        receiverPhoto;
    Boolean read;
    for (DataSnapshot wholeChatData : dataSnapshot.getChildren()) {

        tempMsgList = new ArrayList<>();
        lastTimeStamp = 0;

        for (DataSnapshot data : wholeChatData.getChildren()) {
            msgTime = data.child(NODE_TIMESTAMP).getValue().toString();
            if (Long.parseLong(msgTime) > lastTimeStamp) {
                lastTimeStamp = Long.parseLong(msgTime);
            }
            text = data.child(NODE_TEXT).getValue().toString();
            senderId = data.child(NODE_SENDER_ID).getValue().toString();
            senderName = data.child(NODE_SENDER_NAME).getValue().toString();
            senderPhoto = data.child(NODE_SENDER_PHOTO).getValue().toString();
            receiverId = data.child(NODE_RECEIVER_ID).getValue().toString();
            receiverName = data.child(NODE_RECEIVER_NAME).getValue().toString();
            receiverPhoto = data.child(NODE_RECEIVER_PHOTO).getValue().toString();
            //Node isRead is added later, may be null
            read = data.child(NODE_IS_READ).getValue() == null ||
                Boolean.parseBoolean(data.child(NODE_IS_READ).getValue().toString());

            tempMsgList.add(
                new ChatMessage(text, msgTime, receiverId, receiverName, receiverPhoto,
                    senderId, senderName, senderPhoto, read));
        }

        for (ChatMessage oneTemp : tempMsgList) {
            if ((set.readSetting(Constants.PREF_MY_ID).equals(oneTemp.getReceiver().getId()))) {
                if (oneTemp.getTimestamp().equals(String.valueOf(lastTimeStamp)) &&
                    !oneTemp.isRead()) {
                    lastChats.add(oneTemp);
                }
            }
        }
    }
    return lastChats;
}
 
Example 17
Source File: ShoppingCartWindow.java    From NITKart with MIT License 4 votes vote down vote up
private void setUpShoppingCart(DataSnapshot dataSnapshot) {

        totalAmount = 0;

        if (items != null){
            items.clear();
        } else {
            items = new ArrayList<>();
        }

        for (DataSnapshot snap : dataSnapshot.getChildren()){

            int itemPrice = -1, quantity = 0;

            try{
                itemPrice = Integer.valueOf(NumberFormat.getCurrencyInstance()
                        .parse(String.valueOf(snap.child("price").getValue()))
                        .toString());
            } catch (ParseException e){
                e.printStackTrace();
            }

            quantity = Integer.valueOf(snap.child("quantity").getValue().toString());

            items.add(new ShoppingItem(
                    snap.child("productID").getValue().toString(),
                    snap.child("title").getValue().toString(),
                    snap.child("type").getValue().toString(),
                    snap.child("description").getValue().toString(),
                    itemPrice,
                    quantity
            ));

            totalAmount += quantity*itemPrice;
        }

        ListView view = (ListView) findViewById(R.id.shoppingCartList);
        // Now the Cart gets updated whenever the data changes in the server
        view.setAdapter(new ShoppingCartAdapter(getApplicationContext(), items));

        priceView.setText(NumberFormat.getCurrencyInstance().format(totalAmount));
    }
 
Example 18
Source File: FirestackDatabase.java    From react-native-firestack with MIT License 4 votes vote down vote up
private <Any> Any castSnapshotValue(DataSnapshot snapshot) {
  if (snapshot.hasChildren()) {
    WritableMap data = Arguments.createMap();
    for (DataSnapshot child : snapshot.getChildren()) {
      Any castedChild = castSnapshotValue(child);
      switch (castedChild.getClass().getName()) {
        case "java.lang.Boolean":
          data.putBoolean(child.getKey(), (Boolean) castedChild);
          break;
        case "java.lang.Long":
          data.putDouble(child.getKey(), (Long) castedChild);
          break;
        case "java.lang.Double":
          data.putDouble(child.getKey(), (Double) castedChild);
          break;
        case "java.lang.String":
          data.putString(child.getKey(), (String) castedChild);
          break;
        case "com.facebook.react.bridge.WritableNativeMap":
          data.putMap(child.getKey(), (WritableMap) castedChild);
          break;
      }
    }
    return (Any) data;
  } else {
    if (snapshot.getValue() != null) {
      String type = snapshot.getValue().getClass().getName();
      switch (type) {
        case "java.lang.Boolean":
          return (Any)((Boolean) snapshot.getValue());
        case "java.lang.Long":
          return (Any) ((Long) snapshot.getValue());
        case "java.lang.Double":
          return (Any)((Double) snapshot.getValue());
        case "java.lang.String":
          return (Any)((String) snapshot.getValue());
        default:
          return (Any) null;
      }
    } else {
      return (Any) null;
    }
  }
}
 
Example 19
Source File: FirestackUtils.java    From react-native-firestack with MIT License 4 votes vote down vote up
public static <Any> Any castSnapshotValue(DataSnapshot snapshot) {
  if (snapshot.hasChildren()) {
    WritableMap data = Arguments.createMap();
    for (DataSnapshot child : snapshot.getChildren()) {
      Any castedChild = castSnapshotValue(child);
      switch (castedChild.getClass().getName()) {
        case "java.lang.Boolean":
          data.putBoolean(child.getKey(), (Boolean) castedChild);
          break;
        case "java.lang.Long":
          Long longVal = (Long) castedChild;
          data.putDouble(child.getKey(), (double)longVal);
          break;
        case "java.lang.Double":
          data.putDouble(child.getKey(), (Double) castedChild);
          break;
        case "java.lang.String":
          data.putString(child.getKey(), (String) castedChild);
          break;
        case "com.facebook.react.bridge.WritableNativeMap":
          data.putMap(child.getKey(), (WritableMap) castedChild);
          break;
        default:
          Log.w(TAG, "Invalid type: " + castedChild.getClass().getName());
          break;
      }
    }
    return (Any) data;
  } else {
    if (snapshot.getValue() != null) {
      String type = snapshot.getValue().getClass().getName();
      switch (type) {
        case "java.lang.Boolean":
          return (Any)(snapshot.getValue());
        case "java.lang.Long":
          return (Any)(snapshot.getValue());
        case "java.lang.Double":
          return (Any)(snapshot.getValue());
        case "java.lang.String":
          return (Any)(snapshot.getValue());
        default:
          Log.w(TAG, "Invalid type: "+type);
          return (Any) null;
      }
    }
    return (Any) null;
  }
}
 
Example 20
Source File: DumpFeedback.java    From white-label-event-app with Apache License 2.0 4 votes vote down vote up
private void writeFeedbackTsv(final DataSnapshot data) throws IOException {
    writer.write("session_id\tuser_id\n");
    for (final DataSnapshot session : data.getChildren()) {
        writeSessionRow(session);
    }
}