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

The following examples show how to use com.google.firebase.database.DataSnapshot#getValue() . 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: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportFormatIncludesPriorities()
    throws TimeoutException, InterruptedException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  Map<String, Object> expected = new MapBuilder().put("foo",
      new MapBuilder()
          .put("bar", new MapBuilder().put(".priority", 7.0).put(".value", 5L).build())
          .put(".priority", "hi").build())
      .build();
  ReadFuture readFuture = ReadFuture.untilNonNull(ref);
  ref.setValueAsync(expected);
  DataSnapshot snap = readFuture.timedGet().get(0).getSnapshot();
  Object result = snap.getValue(true);
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 2
Source File: QueryConnectionStatus.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void onDataChange(DataSnapshot dataSnapshot) {
    if (promise == null) return;
    Boolean connected = dataSnapshot.getValue(Boolean.class);
    if (connected != null && connected) {
        promise.doComplete(ConnectionStatus.CONNECTED);
    } else {
        promise.doComplete(ConnectionStatus.DISCONNECTED);
    }
}
 
Example 3
Source File: ClusterMapContributeActivity.java    From intra42 with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    GenericTypeIndicator<HashMap<String, Cluster>> t = new GenericTypeIndicator<HashMap<String, Cluster>>() {
    };
    HashMap<String, Cluster> data = dataSnapshot.getValue(t);

    if (data != null) {
        clusters = new ArrayList<>(data.values());
        Collections.sort(clusters);
    }

    refresh();
}
 
Example 4
Source File: ChatLoginActivity.java    From chat21-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
private static IChatUser decodeContactSnapShop(DataSnapshot dataSnapshot) throws ChatFieldNotFoundException {
        Log.v(TAG, "decodeContactSnapShop called");

        Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();

//        String contactId = dataSnapshot.getKey();

        String uid = (String) map.get("uid");
        if (uid == null) {
            throw new ChatFieldNotFoundException("Required uid field is null for contact id : " + uid);
        }

//        String timestamp = (String) map.get("timestamp");

        String lastname = (String) map.get("lastname");
        String firstname = (String) map.get("firstname");
        String imageurl = (String) map.get("imageurl");
        String email = (String) map.get("email");


        IChatUser contact = new ChatUser();
        contact.setId(uid);
        contact.setEmail(email);
        contact.setFullName(firstname + " " + lastname);
        contact.setProfilePictureUrl(imageurl);

        Log.v(TAG, "decodeContactSnapShop.contact : " + contact);

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

  new WriteFuture(ref,
      new MapBuilder().put("-1", "minus-one").put("0", "zero").put("1", "one").build())
          .timedGet();

  DataSnapshot snap = TestHelpers.getSnap(ref);
  Map<String, Object> expected = new MapBuilder().put("-1", "minus-one").put("0", "zero")
      .put("1", "one").build();
  Object result = snap.getValue();
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 6
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateChangesAreStoredCorrectlyInServer()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  new WriteFuture(writer,
      new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4).build()).timedGet();

  final Semaphore semaphore = new Semaphore(0);
  writer.updateChildren(MapBuilder.of("a", 42),
      new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError error, DatabaseReference ref) {
          assertNull(error);
          semaphore.release(1);
        }
      });

  TestHelpers.waitFor(semaphore);

  DataSnapshot snap = TestHelpers.getSnap(reader);
  Map<String, Object> expected = new MapBuilder().put("a", 42L).put("b", 2L).put("c", 3L)
      .put("d", 4L).build();
  Object result = snap.getValue();
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 7
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheInvalidation()
    throws InterruptedException, TestFailure, TimeoutException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  final AtomicBoolean startChecking = new AtomicBoolean(false);
  final Semaphore ready = new Semaphore(0);
  final ReadFuture future = new ReadFuture(reader.limitToLast(2), 
      new ReadFuture.CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          DataSnapshot snap = events.get(events.size() - 1).getSnapshot();
          Object result = snap.getValue();
          if (startChecking.compareAndSet(false, true) && result == null) {
            ready.release(1);
            return false;
          }
          // We already initialized the location, and now the remove has
          // happened
          // so that
          // we have no more data
          return startChecking.get() && result == null;
        }
      });

  TestHelpers.waitFor(ready);
  for (int i = 0; i < 4; ++i) {
    writer.child("k" + i).setValueAsync(i);
  }

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

  final ReadFuture parentFuture = ReadFuture.untilCountAfterNull(ref.limitToLast(1), 2);

  final List<DataSnapshot> childSnaps = new ArrayList<>();
  ref.child("a").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      childSnaps.add(snapshot);
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });

  new WriteFuture(ref, MapBuilder.of("a", 1, "b", 2)).timedGet();
  assertEquals(1L, childSnaps.get(0).getValue());
  ref.updateChildrenAsync(MapBuilder.of("c", 3));
  List<EventRecord> events = parentFuture.timedGet();
  DataSnapshot snap = events.get(0).getSnapshot();
  Object result = snap.getValue();

  Map<String, Object> expected = MapBuilder.of("b", 2L);
  TestHelpers.assertDeepEquals(expected, result);

  snap = events.get(1).getSnapshot();
  result = snap.getValue();

  expected = MapBuilder.of("c", 3L);
  TestHelpers.assertDeepEquals(expected, result);
  assertEquals(1, childSnaps.size());
  assertEquals(1L, childSnaps.get(0).getValue());
}
 
Example 9
Source File: PostDetailActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();

    // Add value event listener to the post
    // [START post_value_event_listener]
    ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get Post object and use the values to update the UI
            Post post = dataSnapshot.getValue(Post.class);
            // [START_EXCLUDE]
            binding.postAuthorLayout.postAuthor.setText(post.author);
            binding.postTextLayout.postTitle.setText(post.title);
            binding.postTextLayout.postBody.setText(post.body);
            // [END_EXCLUDE]
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            // [START_EXCLUDE]
            Toast.makeText(PostDetailActivity.this, "Failed to load post.",
                    Toast.LENGTH_SHORT).show();
            // [END_EXCLUDE]
        }
    };
    mPostReference.addValueEventListener(postListener);
    // [END post_value_event_listener]

    // Keep copy of post listener so we can remove it when app stops
    mPostListener = postListener;

    // Listen for comments
    mAdapter = new CommentAdapter(this, mCommentsReference);
    binding.recyclerPostComments.setAdapter(mAdapter);
}
 
Example 10
Source File: DataSnapshotMapper.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
private static <U> U getDataSnapshotTypedValue(DataSnapshot dataSnapshot, Class<U> clazz) {
    U value = dataSnapshot.getValue(clazz);
    if (value == null) {
        throw Exceptions.propagate(new RxFirebaseDataCastException(
                "unable to cast firebase data response to " + clazz.getSimpleName()));
    }
    return value;
}
 
Example 11
Source File: SessionFeedbackFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    LOGGER.fine("Answers");
    LOGGER.fine(dataSnapshot.toString());
    priorAnswers = dataSnapshot.getValue(new GenericTypeIndicator<List<Object>>() {});
    if (priorAnswers == null) {
        priorAnswers = new ArrayList<>();
    }
    updateUi();
}
 
Example 12
Source File: FirebaseQueryLiveDataSet.java    From budgetto with MIT License 5 votes vote down vote up
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
    T item = dataSnapshot.getValue(genericTypeClass);
    String key = dataSnapshot.getKey();

    if (liveDataSetIndexes.contains(key)) {
        int index = liveDataSetIndexes.indexOf(key);
        T oldItem = liveDataSetEntries.get(index);
        liveDataSetEntries.set(index, item);
        liveDataSet.setItemChanged(index);
        setValue(new FirebaseElement<>(liveDataSet));

    }
}
 
Example 13
Source File: FirebaseQueryLiveDataSet.java    From budgetto with MIT License 5 votes vote down vote up
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
    T item = dataSnapshot.getValue(genericTypeClass);

    String key = dataSnapshot.getKey();
    if (!liveDataSetIndexes.contains(key)) {
        int insertedPosition;
        if (previousChildName == null) {
            liveDataSetEntries.add(0, item);
            liveDataSetIndexes.add(0, key);
            insertedPosition = 0;
        } else {
            int previousIndex = liveDataSetIndexes.indexOf(previousChildName);
            int nextIndex = previousIndex + 1;
            if (nextIndex == liveDataSetEntries.size()) {
                liveDataSetEntries.add(item);
                liveDataSetIndexes.add(key);
            } else {
                liveDataSetEntries.add(nextIndex, item);
                liveDataSetIndexes.add(nextIndex, key);
            }
            insertedPosition = nextIndex;
        }

        liveDataSet.setItemInserted(insertedPosition);
        setValue(new FirebaseElement<>(liveDataSet));
    }
}
 
Example 14
Source File: ClassSnapshotParser.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public T parseSnapshot(@NonNull DataSnapshot snapshot) {
    // In FirebaseUI controlled usages, we can guarantee that our getValue calls will be nonnull
    // because we check for nullity with ValueEventListeners and use ChildEventListeners.
    // However, since this API is public, devs could use it for any snapshot including null
    // ones. Hence the nullability discrepancy.
    return snapshot.getValue(mClass);
}
 
Example 15
Source File: FavSessionButtonManager.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onChildChanged(DataSnapshot data, String previousChildName) {
    final String session_id = data.getKey();
    boolean is_fav = data.getValue(Boolean.class);
    if (is_fav) {
        favorites.add(session_id);
    }
    else {
        favorites.remove(session_id);
    }
    updateButtons(session_id);
}
 
Example 16
Source File: FirebaseDatabaseHelpers.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
public static List<FeedbackQuestion> toFeedbackQuestions(final DataSnapshot data) {
    final List<FeedbackQuestion2> questions = data.getValue(new GenericTypeIndicator<List<FeedbackQuestion2>>() {});
    int size = questions != null ? questions.size() : 0;
    ArrayList<FeedbackQuestion> qs = new ArrayList<>(size);
    if (questions != null) {
        for (final FeedbackQuestion2 q : questions) {
            qs.add(new FeedbackQuestion(QuestionType.valueOf(q.getType()), q.getText()));
        }
    }
    return qs;

}
 
Example 17
Source File: FirebaseCartLiveData.java    From android-instant-apps-demo with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    catalog = dataSnapshot.getValue(Catalog.class);
    onDataChanged();
}
 
Example 18
Source File: FirebaseDatabaseHelpers.java    From white-label-event-app with Apache License 2.0 4 votes vote down vote up
public static Event toEvent(final DataSnapshot data) {
    return data.getValue(Event.class);
}
 
Example 19
Source File: ConversationMessagesHandler.java    From chat21-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
     * @param dataSnapshot the datasnapshot to decode
     * @return the decoded message
     */
    public static Message decodeMessageSnapShop(DataSnapshot dataSnapshot) throws ChatFieldNotFoundException {
        Log.v(TAG, "decodeMessageSnapShop called");

        Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();

        String messageId = dataSnapshot.getKey();

        String sender = (String) map.get("sender");
        if (sender == null) {
            throw new ChatFieldNotFoundException("Required sender field is null for message id : " + messageId);
        }

        String recipient = (String) map.get("recipient");
        if (recipient == null) {
            throw new ChatFieldNotFoundException("Required recipient field is null for message id : " + messageId);
        }

        String sender_fullname = (String) map.get("sender_fullname");
        String recipient_fullname = (String) map.get("recipient_fullname");

        Long status = null;
        if (map.containsKey("status")) {
            status = (Long) map.get("status");
        }

        String text = (String) map.get("text");

        Long timestamp = null;
        if (map.containsKey("timestamp")) {
            timestamp = (Long) map.get("timestamp");
        }

        String type = (String) map.get("type");

        String channelType = (String) map.get("channel_type");

        // if metadata is a string ignore it
        Map<String, Object> metadata = null;
        if (map.containsKey("metadata") && !(map.get("metadata") instanceof String)) {
            metadata = (Map<String, Object>) map.get("metadata");
        }

        // if metadata is a string ignore it
        Map<String, Object> attributes = null;
        if (map.containsKey("attributes") && !(map.get("attributes") instanceof String)) {
            attributes = (Map<String, Object>) map.get("attributes");
        }

        Message message = new Message();

        message.setId(messageId);
        message.setSender(sender);
        message.setSenderFullname(sender_fullname);
        message.setRecipient(recipient);
        message.setRecipientFullname(recipient_fullname);
        message.setStatus(status);
        message.setText(text);
        message.setTimestamp(timestamp);
        message.setType(type);
        message.setChannelType(channelType);
        if (metadata != null) message.setMetadata(metadata);
        if (attributes != null) message.setAttributes(attributes);

        Log.v(TAG, "decodeMessageSnapShop.message : " + message);

//        Log.d(TAG, "message >: " + dataSnapshot.toString());

        return message;
    }
 
Example 20
Source File: FirebaseDatabaseHelpers.java    From white-label-event-app with Apache License 2.0 4 votes vote down vote up
public static AttendeeItem toAttendeeItem(final DataSnapshot data) {
    return data.getValue(AttendeeItem.class);
}