/** * Get a FollowRequest from Firebase. * @param key * @param resultListener */ @Override public void get(String key, final OnResultListener<FollowRequest> resultListener) { mFollowRequestRef.child(key).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { FollowRequest request = dataSnapshot.getValue(FollowRequest.class); resultListener.onResult(request); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
public void getNowListening(String uid, final OnCompleteGetNowListening listener) { rdm.getUsersReference().child(uid).child("now").addValueEventListener( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String state = dataSnapshot.getValue(String.class); if (state == null) return; Log.e(TAG, "getNowListening:complete, " + state); listener.onComplete(state); } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, "getNowListening:onCancelled", databaseError.toException()); } }); }
private void setUser(){ reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { User user = snapshot.getValue(User.class); users.add(user); } name.setText(users.get(0).getResults().get(0).getName().getFirst()); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
private void buildValueListener() { try { Log.i(TAG, "Building value listener"); mValueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { processJSONResult(dataSnapshot, null, false); } @Override public void onCancelled(DatabaseError databaseError) { Log.i(TAG, "ValueEventListener:onCancelled" + databaseError.getMessage()); mDatabaseComponent.removeListener(listenerID); mValueEventListener = null; callbackContext.error(databaseError.getMessage()); } }; } catch (Exception e) { Log.e(TAG, "Error building query"); callbackContext.error(e.getMessage()); } }
public void removeDetectiveProcess(ViewAppHolder.UserProfileViewHolder userProfileViewHolder, Context context){ FirebaseHelper.getUserAccountSettings(USER_LINK_FIREBASE) .child(Constants.DETECTION_MODE).setValue(Constants.USER_DETECTION_INACTIVE); userProfileViewHolder.DETECTION_ICON.setImageTintList( context.getResources().getColorStateList(R.color.safe_color)); FirebaseHelper.getUserFriendList(USER_LINK_FIREBASE) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){ FirebaseHelper.getUserDetection(Utility.encodeUserEmail(dataSnapshot1.getValue(String.class))) .child(USER_LINK_FIREBASE).removeValue(); } FirebaseHelper.getUserLocation(USER_LINK_FIREBASE) .removeEventListener(userDetectionLocationListener); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
@Test public void testSetDataMultipleTimesEnsureValueIsCalledAppropriately() throws TestFailure, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ; ReadFuture readFuture = ReadFuture.untilEquals(ref, 2L, /*ignoreFirstNull=*/ true); ZombieVerifier.verifyRepoZombies(ref); for (int i = 0; i < 3; ++i) { ref.setValueAsync(i); } List<EventRecord> events = readFuture.timedGet(); for (long i = 0; i < 3; ++i) { DataSnapshot snap = events.get((int) i).getSnapshot(); assertEquals(i, snap.getValue()); } ZombieVerifier.verifyRepoZombies(ref); }
private void setDistanceRemainingToUI(final DatabaseReference databaseReference, FirebaseUser firebaseUser) { databaseReference.child("global") .child("distanceRemaining") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the android UI setDistanceRemainingToUI(dataSnapshot.getValue(Long.class).intValue()); } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); }
@Test public void correctlySetUserReady() { firebaseHelper.setUserStatus("testChallenge", "testUser1", FirebaseNodes.ChallengeStatus.READY, true); firebaseHelper.getDatabase().child(FirebaseNodes.CHALLENGES).child("testChallenge") .child("testUser1").child(FirebaseNodes.ChallengeStatus.READY.toString()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Assert.assertTrue(dataSnapshot.exists()); Assert.assertTrue((boolean)dataSnapshot.getValue()); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
private void deleteHelpRequest(){ FirebaseHelper.getUserFriendList(USER_LINK_FIREBASE) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){ FirebaseHelper.getUserHelpRequest(Utility.encodeUserEmail(dataSnapshot1.getValue(String.class))) .child(USER_LINK_FIREBASE).removeValue(); Log.e("help ",dataSnapshot1.getKey()); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
/** * Get how long the user has been a botanist * @return Returns the total number of added plants */ private long getAddedCount() { getUserReference().child("plantsAdded").addListenerForSingleValueEvent(new ValueEventListener() { /** * Handle a change in the database contents * @param snapshot - current database contents */ @Override public void onDataChange(DataSnapshot snapshot) { if (snapshot.exists()) { mPlantsAdded = (long) snapshot.getValue(); } } /** * Do nothing when the process is cancelled * @param databaseError - Ignored error */ @Override public void onCancelled(DatabaseError databaseError) { } }); return mPlantsAdded; }
@Override public void onDataChange(DataSnapshot dataSnapshot) { //If there is an incomplete drive: if (dataSnapshot.hasChild("start")) { Log.d(TAG, "There's an incomplete drive in Firebase!"); //Get the starting time from the incomplete value: startingTime.setTimeInMillis((long)dataSnapshot.child("start").getValue()); //If the user has completed the ongoing drive and just needs to go to the dialog if (dataSnapshot.hasChild("end")) { //Get the ending time: endingTime.setTimeInMillis((long)dataSnapshot.child("end").getValue()); //Show the dialog using the driver ID: showDialog(dataSnapshot.child("driver_id").getValue().toString()); } else { //Otherwise, if the drive is still ongoing: //Enable the start button and update the timer label: startButton.setEnabled(false); stopButton.setEnabled(true); timerUpdateLabel(); } } }
public void setNewNotificationsListener (final TextView notificationTextView){ FirebaseHelper.getUserNewNotificationsNumber(USER_LINK_FIREBASE) .addValueEventListener(newNotificationsListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Integer newNotificationsNumber = dataSnapshot.getValue(Integer.class); if(newNotificationsNumber != null && newNotificationsNumber > 0) { notificationTextView.setVisibility(View.VISIBLE); notificationTextView.setText(String.valueOf(newNotificationsNumber)); }else{ notificationTextView.setVisibility(View.GONE); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
/** * Check flags state */ private void flagsSettingsToActive(){ FirebaseHelper.getUserAccountSettings(USER_LINK_FIREBASE) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { final boolean PUBLIC_FLAG_MARKERS_ACTIVE_STATE = dataSnapshot.getValue(AccountSettings.class).getShowPublicFlags(); final boolean FRIENDS_FLAG_MARKERS_ACTIVE_STATE = dataSnapshot.getValue(AccountSettings.class).getShowFriendsFlags(); if(PUBLIC_FLAG_MARKERS_ACTIVE_STATE){ setupFlagsPublicMarkers(); } if(FRIENDS_FLAG_MARKERS_ACTIVE_STATE){ setupFlagsFriendsMarkers(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
@Test public void testAttachingListener() { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); ValueEventListener listener = ref.limitToLast(1) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // No-op } @Override public void onCancelled(DatabaseError error) { } }); assertNotNull(listener); }
@Test public void testNullPrioritiesIncludedInStartAt() throws InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); ref.setValueAsync( new MapBuilder() .put("a", new MapBuilder().put(".priority", null).put(".value", 0).build()) .put("b", new MapBuilder().put(".priority", null).put(".value", 1).build()) .put("c", new MapBuilder().put(".priority", 2).put(".value", 2).build()) .put("d", new MapBuilder().put(".priority", 3).put(".value", 3).build()) .put("e", new MapBuilder().put(".priority", "hi").put(".value", 4).build()).build()); DataSnapshot snap = TestHelpers.getSnap(ref.startAt(2)); Object result = snap.getValue(); Map<String, Object> expected = MapBuilder.of("c", 2L, "d", 3L, "e", 4L); TestHelpers.assertDeepEquals(expected, result); }
private void postComment() { final String uid = getUid(); FirebaseDatabase.getInstance().getReference().child("users").child(uid) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get user information String authorName = user.getDisplayName(); // Create new comment object String commentText = mCommentField.getText().toString(); Comment comment = new Comment(uid, authorName, commentText); // Push the comment, it will appear in the list mCommentsReference.push().setValue(comment); // Clear the field mCommentField.setText(null); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
public void incrementWatchersCount(String postId) { DatabaseReference postRef = database.getReference("posts/" + postId + "/watchersCount"); postRef.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { Integer currentValue = mutableData.getValue(Integer.class); if (currentValue == null) { mutableData.setValue(1); } else { mutableData.setValue(currentValue + 1); } return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { LogUtil.logInfo(TAG, "Updating Watchers count transaction is completed."); } }); }
@Override public void onDataChange(DataSnapshot dataSnapshot) { postsList.clear(); postListForward.clear(); printLog(TAG, dataSnapshot.getChildrenCount() + "on single time data change"); Iterable iterable = dataSnapshot.getChildren(); Iterator iterator = iterable.iterator(); while (iterator.hasNext()) { DataSnapshot dataSnapshot1 = (DataSnapshot) iterator.next(); HashMap hashMap = (HashMap) dataSnapshot1.getValue(); String str = (String) hashMap.get(dataSnapshot1.getKey()); PostModel postModel = new PostModel(hashMap); postsList.add(postModel); } postListForward.addAll(postsList); Collections.reverse(postsList); Collections.reverse(postListForward); AgroStarApplication.getInstance().triggerPostAdded(postListForward); AgroStarApplication.getDatabaseInstance().getReference().child(TABLENAME).addChildEventListener(this); }
protected void searchWithoutFilter() { final String keyword = etSearch.getText().toString().trim(); Query query = mDatabase.orderByChild("category").equalTo(keyword); mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot snap : dataSnapshot.getChildren()) { String itemName = snap.child("itemName").getValue(String.class); if(itemName.toLowerCase().contains(keyword.toLowerCase())) { items.add(itemName); itemKeys.add(snap.getKey()); } } loadListView(); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
@Override public void onDataChange(DataSnapshot dataSnapshot) { EditText username = (EditText)findViewById(R.id.usernameText); name = username.getText().toString(); EditText password = (EditText)findViewById(R.id.passwordText); pass = password.getText().toString(); Spinner grabAccountType = findViewById(R.id.accountTypeSpinner); String accountType = (String) grabAccountType.getSelectedItem(); if (!(dataSnapshot.child(email).hasChild(name))) { if (accountType.equals("Child")) { newUser = new User(name, pass, MenuActivity.getManager().nextSerialNumber(), resID); manager.setCurrentUserId(newUser.getUserId()); manager.addRegUser(newUser); fbRef.child(email).child("ChoreManager").setValue(manager); } else { newAdminUser = new AdminUser(name, pass, MenuActivity.getManager().nextSerialNumber(), resID); manager.setCurrentUserId(newAdminUser.getUserId()); manager.addAdminUser(newAdminUser); fbRef.child(email).child("ChoreManager").setValue(manager); } } finish(); }
@Override protected OrderItem convert(DataSnapshot data) { OrderItem orderItem = new OrderItem(); orderItem.setId(data.getKey()); for (DataSnapshot d : data.getChildren()) { if (d.getKey().equals(DIFFERENT_FEATURE_REFERENCE)) { orderItem.setDifferentFeature(d.getValue(String.class)); } else if (d.getKey().equals(PAYED_REFERENCE)) { orderItem.setPaid(d.getValue(Boolean.class)); } else if (d.getKey().equals(READY_REFERENCE)) { orderItem.setReady(d.getValue(Boolean.class)); } else if (d.getKey().equals(DELIVERED_REFERENCE)) { orderItem.setDelivered(d.getValue(Boolean.class)); } else if (d.getKey().equals(DISH_ID_REFERENCE)) { orderItem.setDishId(d.getValue(String.class)); } else if (d.getKey().equals(MENU_ID_REFERENCE)) { orderItem.setMenuId(d.getValue(String.class)); } } return orderItem; }
@Test public void testSetOverwritesPriorityOfTopLevelNodesAndChildren() throws ExecutionException, TimeoutException, InterruptedException, TestFailure { List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2); final DatabaseReference ref1 = refs.get(0); final DatabaseReference ref2 = refs.get(1); ref1.setValueAsync(new MapBuilder().put("a", 5).build()); ref1.setPriorityAsync(10); ref1.child("a").setPriorityAsync(18); new WriteFuture(ref1, new MapBuilder().put("a", 7).build()).timedGet(); DataSnapshot snap = new ReadFuture(ref2).timedGet().get(0).getSnapshot(); assertNull(snap.getPriority()); assertNull(snap.child("a").getPriority()); }
public Promise<Boolean, BError, Void> isOnline(){ final Deferred<Boolean, BError, Void> deferred = new DeferredObject<>(); if (currentUserModel() == null) { return deferred.reject(BError.getError(BError.Code.NULL, "Current user is null")); } FirebasePaths.userOnlineRef(currentUserModel().getEntityID()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { updateLastOnline(); deferred.resolve((Boolean) snapshot.getValue()); } @Override public void onCancelled(DatabaseError firebaseError) { deferred.reject(getFirebaseError(firebaseError)); } }); return deferred.promise(); }
@Test public void testNameAndRefForSnapshots() throws TestFailure, ExecutionException, TimeoutException, InterruptedException { DatabaseReference ref = FirebaseDatabase.getInstance(masterApp).getReference(); // Clear any data there new WriteFuture(ref, MapBuilder.of("foo", 10)).timedGet(); DataSnapshot snap = TestHelpers.getSnap(ref); assertNull(snap.getKey()); assertEquals(ref.toString(), snap.getRef().toString()); DataSnapshot childSnap = snap.child("a"); assertEquals("a", childSnap.getKey()); assertEquals(ref.child("a").toString(), childSnap.getRef().toString()); childSnap = childSnap.child("b/c"); assertEquals("c", childSnap.getKey()); assertEquals(ref.child("a/b/c").toString(), childSnap.getRef().toString()); }
@Test public void testUpdateAffectPriorityLocally() throws TestFailure, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); ReadFuture readFuture = ReadFuture.untilCountAfterNull(ref, 2); ref.setValueAsync(new MapBuilder().put("a", 1).put("b", 2).put("c", 3).build(), "testpri"); ref.updateChildrenAsync(MapBuilder.of("a", 4)); List<EventRecord> events = readFuture.timedGet(); DataSnapshot snap = events.get(0).getSnapshot(); assertEquals("testpri", snap.getPriority()); snap = events.get(1).getSnapshot(); assertEquals(4L, snap.child("a").getValue()); assertEquals("testpri", snap.getPriority()); }
public void setUserRelation(final String USER_EMAIL, final ViewAppHolder.SearchViewHolder searchViewHolder){ FirebaseHelper.getUserDatabaseReference(USER_LINK_FIREBASE) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { boolean userInFriendList = checkUserInFriendList(dataSnapshot,USER_EMAIL); boolean userInFriendRequest = checkUserInFriendRequest(dataSnapshot,USER_EMAIL); boolean currentUserSendFriendRequest = checkCurrentUserRequestSend(dataSnapshot,USER_EMAIL); userSearchUi.setUserView(userInFriendList, userInFriendRequest, currentUserSendFriendRequest, searchViewHolder, USER_EMAIL); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
/** * Fetch habit event from the database * @param key the habit event key * @param resultListener result callback */ @Override public void get(String key, final OnResultListener<HabitEvent> resultListener) { mHabitEventsRef.child(key).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { HabitEventDataModel model = dataSnapshot.getValue(HabitEventDataModel.class); if(model != null) { resultListener.onResult(model.getHabitEvent()); } else { resultListener.onResult(null); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
@Override public DataEvent createEvent(Change change, QuerySpec query) { DataSnapshot snapshot; if (change.getEventType() == Event.EventType.VALUE) { snapshot = InternalHelpers.createDataSnapshot( InternalHelpers.createReference(null, query.getPath()), change.getIndexedNode()); } else { snapshot = InternalHelpers.createDataSnapshot( InternalHelpers.createReference(null, query.getPath().child(change.getChildKey())), change.getIndexedNode()); } String prevName = change.getPrevName() != null ? change.getPrevName().asString() : null; return new TestEvent(change.getEventType(), snapshot, prevName, this); }
@Override public void onDataChange(DataSnapshot dataSnapshot) { if((dataSnapshot.child(emailEscaped).child("ChoreManager").child("adminUsers").getChildrenCount()==0)&& counter==0) { counter++; finish(); startActivity(new Intent(AppLoginActivity.this, SpecialAdminUserCreationActivity.class)); } else if (counter==0){ finish(); counter ++; startActivity(new Intent(AppLoginActivity.this, MenuActivity.class)); } }
void saveUserInfo() { Utilities.getFirebaseDBReference().child("/user/" + StaticConfig.UID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.getValue() != null){ waitingDialog.dismiss(); HashMap hashUser = (HashMap) dataSnapshot.getValue(); User userInfo = new User(); userInfo.name = (String) hashUser.get("name"); userInfo.email = (String) hashUser.get("email"); userInfo.avata = (String) hashUser.get("avata"); SharedPreferenceHelper.getInstance(LoginActivity.this).saveUserInfo(userInfo); }else{ User newUser = new User(); newUser.email = user.getEmail(); newUser.name = user.getEmail().substring(0, user.getEmail().indexOf("@")); newUser.avata = StaticConfig.STR_DEFAULT_BASE64; Utilities.getFirebaseDBReference().child("user/" + user.getUid()).setValue(newUser) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { saveUserInfo(); } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
public void isLove(String userId, String artist, String album, String title, final OnCompleteGetLikeState listener) { RemoteDatabaseManager rdm = new RemoteDatabaseManager(); artist = MusicDto.replaceForInput(artist); album = MusicDto.replaceForInput(album); title = MusicDto.replaceForInput(title); rdm.getUsersReference().child(userId).child("like").child(artist+"/"+album+"/"+title).addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { State state = dataSnapshot.getValue(State.class); if (state == null) return; Log.e(TAG, "getLikeState:complete, " + state.getState()); listener.onComplete(state.getState()); } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, "getLikeState:onCancelled", databaseError.toException()); } }); }
@Override public DataEvent createEvent(Change change, QuerySpec query) { DatabaseReference ref = InternalHelpers.createReference(repo, query.getPath()); DataSnapshot dataSnapshot = InternalHelpers.createDataSnapshot(ref, change.getIndexedNode()); return new DataEvent(Event.EventType.VALUE, this, dataSnapshot, null); }
private void initSignIn(DataSnapshot snapshot){ User currentUser = snapshot.getValue(User.class); if (currentUser == null) { registerNewUser(); } helper.changeUserConnectionStatus(User.ONLINE); postEvent(LoginEvent.onSignInSuccess); }
public static void getAppVersion(final OnCompleteGetFirebaseAppVersionListener listener) { DatabaseReference database = getPreferenceReference(); database.child("APP_VERSION").addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { AppVersion ver = dataSnapshot.getValue(AppVersion.class); listener.onComplete(ver); } catch ( Exception e ) { Log.e("tag", "exception"); e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
/** * click on a Challenge Request message from the Challenges tab. * @param message the Challenge Request Message. */ @Override public void onMessagesFragmentInteraction(final Message message) { if(message == null){ throw new IllegalArgumentException("Invalid argument 'message' on onMessagesFragmentInteraction method"); } requestMessage = message; if (message.getType() == Message.Type.CHALLENGE_REQUEST) { final String challengeName = FirebaseProxy.generateChallengeName( message.getSender(), message.getAddressee(), message.getMessage()); DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); dbRef.child("challenges").child(challengeName) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { showRequestChallengeDialog(); } else { Toast.makeText(getBaseContext(), "Opponent has already deleted this challenge", Toast.LENGTH_LONG).show(); FirebaseHelper fbHelper = new FirebaseHelper(); fbHelper.deleteChallengeNode(challengeName); fbHelper.deleteMessage(message); launchFragment(new MessagesFragment()); } } @Override public void onCancelled(DatabaseError databaseError) { throw databaseError.toException(); } }); } }
@Test public void testInfoServerTimeOffset() throws TestFailure, TimeoutException, InterruptedException { DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); DataSnapshot snap = new ReadFuture(ref.child(".info/serverTimeOffset")).timedGet().get(0).getSnapshot(); assertTrue(snap.getValue() instanceof Long); }
public void loadDataFromId(final String idx) { Query query = References.getInstance().chatsRef.child(idx); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { Map<String, Object> messageData = (Map<String, Object>) dataSnapshot.getValue(); Message message = new Message(mUser.getIdx(), messageData); Map<String, Object> phones = getMapDataFromData("phones", messageData); if (message.getChatType() == ChatType.PERSONAL) { String key = dataSnapshot.getKey(); String[] userIds = Util.getUserIdsFrom(key); String contactId = null; for (String userId : userIds) { if (!userId.equals(mUser.getIdx())) { contactId = userId; } } mPhoneContactNumber = (String) phones.get(contactId); updateContactName(mPhoneContactNumber); updateData(message, contactId); } else { } } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("ChatListAdapter", databaseError.toString()); } }); updateUnreadCount(0); }
@Test public void testValueIsTriggeredForEmptyNodes() throws TestFailure, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ; DataSnapshot snap = new ReadFuture(ref).timedGet().get(0).getSnapshot(); ZombieVerifier.verifyRepoZombies(ref); assertNull(snap.getValue()); }
@Override @NonNull public Observable<Boolean> setUserOnline(@NonNull String userId) { return Observable.create(subscriber -> { DatabaseReference onlineReference = firebaseDatabase.getReference() .child(FirebaseStructure.ONLINE) .child(userId); DatabaseReference connectionReference = firebaseDatabase.getReference() .child(".info") .child("connected"); connectionReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if ((Boolean) dataSnapshot.getValue()) { onlineReference.onDisconnect().removeValue(); onlineReference.setValue(true); subscriber.onNext(true); subscriber.onCompleted(); } } @Override public void onCancelled(DatabaseError databaseError) { subscriber.onError(databaseError.toException()); } }); }); }