Java 类com.google.firebase.database.DataSnapshot 实例源码

项目:cat-is-a-dog    文件:FollowRequestRepository.java   
/**
 * 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) {

        }
    });
}
项目:pracler    文件:UserManager.java   
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());
                }
            });
}
项目:Android-Developer-Path    文件:MainActivity.java   
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) {

        }
    });
}
项目:cordova-plugin-firebase-sdk    文件:DatabaseListener.java   
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());
    }
}
项目:IM_Here    文件:UserDataFirebase.java   
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) {

                }
            });
}
项目:firebase-admin-java    文件:EventTestIT.java   
@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);
}
项目:Forager    文件:Community.java   
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());
                }
            });
}
项目:Runnest    文件:FirebaseHelperTest.java   
@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) {

                }
            });
}
项目:IM_Here    文件:UserDataFirebase.java   
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) {

                }
            });
}
项目:Botanist    文件:DatabaseManager.java   
/**
 * 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;
}
项目:permitlog-android    文件:HomeFragment.java   
@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();
        }
    }
}
项目:IM_Here    文件:UserDataFirebaseMainActivity.java   
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) {

                }
            });
}
项目:IM_Here    文件:UserDataFirebaseMap.java   
/**
 * 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) {

                }
            });
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@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);
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@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);
}
项目:Quadro    文件:PostDetailActivity.java   
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) {

                }
            });
}
项目:social-app-android    文件:DatabaseHelper.java   
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.");
        }
    });
}
项目:FirebasePost    文件:PostTableService.java   
@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);
}
项目:MavsSnapUp    文件:SearchActivity.java   
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) {

        }
    });
}
项目:Chore-Manager-App    文件:NewUserActivity.java   
@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();
}
项目:wisebite_android    文件:OrderItemRepository.java   
@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;
}
项目:firebase-admin-java    文件:DataTestIT.java   
@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());
}
项目:AndroidBackendlessChat    文件:BChatcatNetworkAdapter.java   
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();
    }
项目:firebase-admin-java    文件:DataTestIT.java   
@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());
}
项目:firebase-admin-java    文件:DataTestIT.java   
@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());
}
项目:IM_Here    文件:UserDataFirebaseSearch.java   
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) {

        }
    });
}
项目:cat-is-a-dog    文件:HabitEventRepository.java   
/**
 * 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) {

        }
    });
}
项目:firebase-admin-java    文件:SyncPointTest.java   
@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);
}
项目:Chore-Manager-App    文件:AppLoginActivity.java   
@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));
    }
}
项目:Show_Chat    文件:LoginActivity.java   
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) {

        }
    });
}
项目:pracler    文件:UserManager.java   
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());
                }
            });
}
项目:firebase-admin-java    文件:ValueEventRegistration.java   
@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);
}
项目:androidadvanced    文件:LoginRepositoryImpl.java   
private void initSignIn(DataSnapshot snapshot){
    User currentUser = snapshot.getValue(User.class);

    if (currentUser == null) {
        registerNewUser();
    }
    helper.changeUserConnectionStatus(User.ONLINE);
    postEvent(LoginEvent.onSignInSuccess);
}
项目:pracler    文件:FirebaseAppVersionManager.java   
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)
                {

                }
            });

}
项目:Runnest    文件:SideBarActivity.java   
/**
 * 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();
            }
        });
    }
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@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);
}
项目:Raffler-Android    文件:ChatListRecyclerViewAdapter.java   
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);
}
项目:firebase-admin-java    文件:EventTestIT.java   
@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());
}
项目:memory-game    文件:DefaultFirebaseOnlineGateway.java   
@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());
            }
        });
    });
}