當前位置: 首頁>>代碼示例>>Java>>正文


Java DatabaseReference.addListenerForSingleValueEvent方法代碼示例

本文整理匯總了Java中com.google.firebase.database.DatabaseReference.addListenerForSingleValueEvent方法的典型用法代碼示例。如果您正苦於以下問題:Java DatabaseReference.addListenerForSingleValueEvent方法的具體用法?Java DatabaseReference.addListenerForSingleValueEvent怎麽用?Java DatabaseReference.addListenerForSingleValueEvent使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.firebase.database.DatabaseReference的用法示例。


在下文中一共展示了DatabaseReference.addListenerForSingleValueEvent方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: deleteGroupFromUser

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private static void deleteGroupFromUser(final String groupId, String userId) {
    final DatabaseReference currentUserGroupsRef = userDataRef.child(userId).child("groups");
    currentUserGroupsRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                if (ds.getValue().equals(groupId)) {
                    currentUserGroupsRef.child(ds.getKey()).removeValue();
                    pullFromFirebase(2); // Fetch group data from Firebase from new list
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
 
開發者ID:a-deda,項目名稱:share-location,代碼行數:20,代碼來源:FirebaseHelper.java

示例2: onBindViewHolder

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
@Override
public void onBindViewHolder(final GridImageHolder holder, int position) {
    DatabaseReference ref = FirebaseUtil.getPostsRef().child(mPostPaths.get(position));
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Post post = dataSnapshot.getValue(Post.class);
            GlideUtil.loadImage(post.getFull_url(), holder.imageView);
            holder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO: Implement go to post view.
                    Toast.makeText(UserDetailActivity.this, "Selected: " + holder
                            .getAdapterPosition(),
                            Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
            Log.e(TAG, "Unable to load grid image: " + firebaseError.getMessage());
        }
    });
}
 
開發者ID:firebase,項目名稱:friendlypix-android,代碼行數:26,代碼來源:UserDetailActivity.java

示例3: recieveData

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private void recieveData() {
    // Get the Firebase node to write the  read data from
    DatabaseReference refDatabase = FirebaseDatabase.getInstance().getReference("Serving");
    refDatabase.addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            collectLocationsAndPutOnMap((Map<String, Object>) dataSnapshot.getValue());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }


    });
}
 
開發者ID:thandomy,項目名稱:foodie,代碼行數:19,代碼來源:HomeActivity.java

示例4: addLike

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private void addLike(final Feed feed){
    flagLike = true;
    final DatabaseReference referenceLike = FirebaseDatabase.getInstance().getReference().child(LIKE_ROOT);
    final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser();
    referenceLike.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (flagLike){
                if (dataSnapshot.child( feed.getIdFeed() ).hasChild( auth.getUid())){
                    referenceLike.child(feed.getIdFeed()).child(auth.getUid()).removeValue();
                    flagLike = false;
                }else{
                    referenceLike.child(feed.getIdFeed()).child(auth.getUid()).setValue(true);
                    flagLike = false;
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
 
開發者ID:AleBarreto,項目名稱:FeedFire,代碼行數:25,代碼來源:MainActivity.java

示例5: isProfileExist

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
public void isProfileExist(String id, final OnObjectExistListener<Profile> onObjectExistListener) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child("profiles").child(id);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            onObjectExistListener.onDataChanged(dataSnapshot.exists());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
 
開發者ID:rozdoum,項目名稱:social-app-android,代碼行數:15,代碼來源:ProfileManager.java

示例6: threadDeletedDate

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
/**
 * Get the date when the thread was deleted
 * @return Promise On success return the date or Nil if the thread hasn't been deleted
 **/
public Promise<Long, DatabaseError, Void> threadDeletedDate(){
    final Deferred<Long, DatabaseError, Void> deferred = new DeferredObject<>();

    BUser user = getNetworkAdapter().currentUserModel();
    
    DatabaseReference currentThreadUser = FirebasePaths.threadRef(entityId)
            .child(BFirebaseDefines.Path.BUsersPath)
            .child(user.getEntityID())
            .child(BDefines.Keys.BDeleted);;
    
    currentThreadUser.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.getValue() != null)
            {
                deferred.resolve((Long) snapshot.getValue());
            }
            else deferred.resolve(null);
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
            deferred.reject(firebaseError);
        }
    });
    
    return deferred.promise();
}
 
開發者ID:MobileDev418,項目名稱:chat-sdk-android-push-firebase,代碼行數:33,代碼來源:BThreadWrapper.java

示例7: testWritesToSameLocationWhileOfflineAreInOrder

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
@Test
public void testWritesToSameLocationWhileOfflineAreInOrder()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  DatabaseReference.goOffline();
  for (int i = 0; i < 100; i++) {
    ref.setValueAsync(i);
  }
  // This should be the last write and the actual value
  WriteFuture future = new WriteFuture(ref, 100);
  DatabaseReference.goOnline();
  future.timedGet();

  final Semaphore semaphore = new Semaphore(0);
  ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      assertEquals(100L, snapshot.getValue());
      semaphore.release();
    }

    @Override
    public void onCancelled(DatabaseError error) {
      fail("Shouldn't be cancelled");
    }
  });

  TestHelpers.waitFor(semaphore);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:31,代碼來源:RealtimeTestIT.java

示例8: getUserPalaces

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
public List<User> getUserPalaces(final FetchDataCallback callback) {
    if (!mUserPalaces.isEmpty()) {
        mUserPalaces.clear();
    }
    DatabaseReference users = FirebaseDatabase.getInstance().getReference(mResources.getString(R.string.database_users));
    users.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if (snapshot.hasChild(mResources.getString(R.string.database_palace))) {
                    User user = snapshot.getValue(User.class);
                    mUserPalaces.add(user);
                    Log.i("USER ID", user.getUid());
                }
            }

            callback.onDataFetched();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return mUserPalaces;
}
 
開發者ID:AviralGarg1993,項目名稱:VR-One,代碼行數:28,代碼來源:PalaceSelectionActivity.java

示例9: createUserInFirebaseHelper

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
@Override
public void createUserInFirebaseHelper(String uid, final User user) {
    final DatabaseReference userLocation =
            FirebaseDatabase.getInstance().getReferenceFromUrl(Constants.FIREBASE_URL_USERS).child(uid);

    /**
     * See if there is already a user (for example, if they already logged in with an associated
     * Google account.
     */
    userLocation.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            /* If there is no user, make one */
            if (dataSnapshot.getValue() == null) {
             /* Set raw version of date to the ServerValue.TIMESTAMP value and save into dateCreatedMap */
                HashMap<String, Object> timestampJoined = new HashMap<>();
                timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);
                user.setTimestampJoined(timestampJoined);
                userLocation.setValue(user);
            }
        }


        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i("error",databaseError.getMessage());
            mLoginView.showUserCreateErrorMessage();

        }


    });
}
 
開發者ID:Elbehiry,項目名稱:Viajes,代碼行數:34,代碼來源:LoginPresenter.java

示例10: getUserStatistics

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
/**
 * Getter for the statistics of a user. Give them to the given handler to allow their usage in the rest of the
 * application.
 *
 * @param email         Email of the user from which to get statistics.
 * @param handler       Handler who will handle the statistics.
 */
public void getUserStatistics(String email, final statisticsHandler handler){

    final String[] userStatistics = new String[6];

    //Check validity of arguments
    if(email == null) {
        throw new IllegalArgumentException("Email has to be non-null");
    }
    if(email.isEmpty()) {
        throw new IllegalArgumentException("Email must be non empty and " +
                "email length has to be under 100 characters");
    }

    final DatabaseReference statistics = databaseReference.child(FirebaseNodes.USERS).
            child(getFireBaseMail(email)).child(FirebaseNodes.STATISTICS);

    statistics.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for(int i = 0; i < NUMBER_OF_STATISTICS; ++i) {
                    userStatistics[statisticsIndexes[i]] = null;
                    if (dataSnapshot.hasChild(statisticsChildren[i])) {
                        userStatistics[statisticsIndexes[i]] = String.valueOf(dataSnapshot.child(statisticsChildren[i]).getValue());
                    }
                }
                handler.handleRetrievedStatistics(userStatistics);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
}
 
開發者ID:IrrilevantHappyLlamas,項目名稱:Runnest,代碼行數:44,代碼來源:FirebaseHelper.java

示例11: CheckUser

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private void CheckUser() {
        String path = String.format("/users/%s/", FirebaseHelper.getInstance().getAuth().getCurrentUser().getUid());

        DatabaseReference clientIDRef;
        clientIDRef = FirebaseHelper.getInstance().getDatabase().getReference(path);

        ValueEventListener clientIDRefListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String clientID = (String)dataSnapshot.child("clientID").getValue();
                if ((dataSnapshot.child("mobileAppUser").exists()) && (dataSnapshot.child("mobileAppUser").getValue().toString().toLowerCase().equals("true"))) {
                    FirebaseHelper.getInstance().setClientID(clientID);
                    Intent intent = new Intent(MainActivity.this, CowListingActivity.class);
                    startActivity(intent);
                } else {
                    FirebaseHelper.getInstance().setClientID(null);
                    FirebaseHelper.getInstance().getAuth().signOut();
                    AppDialogs.DisplayMessage(MainActivity.this, getString(R.string.error_text), getString(R.string.no_use_permission));
                }
                //dataSnapshot.getValue(String.class);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                FirebaseHelper.getInstance().setClientID(null);
                AppDialogs.DisplayMessage(MainActivity.this, getString(R.string.error_text), getString(R.string.login_problem));
//                clientIDRef.removeEventListener(clientIDRefListener);
            }
        };
        clientIDRef.addListenerForSingleValueEvent(clientIDRefListener);
    }
 
開發者ID:ekalyvio,項目名稱:CowBit,代碼行數:32,代碼來源:MainActivity.java

示例12: deleteUserFromGroup

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
public static void deleteUserFromGroup(final String groupId) {
    final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();

    final DatabaseReference group = groupDataRef.child(groupId);

    group.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.child("members").getChildren()) {
                if (ds.getValue().equals(userId)) {
                    group.child("members").child(ds.getKey()).removeValue(); // Delete value
                    deleteGroupFromUser(groupId, userId); // Delete group reference from user
                }
            }

            // If user was only group member, the group can be deleted.
            if (dataSnapshot.child("members").getChildrenCount() == 1) {
                group.removeValue();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
 
開發者ID:a-deda,項目名稱:share-location,代碼行數:28,代碼來源:FirebaseHelper.java

示例13: getFollows

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
@Override
public Promise<List<BUser>, BError, Void>  getFollows(String entityId){
    if (DEBUG) Timber.v("getFollowers, Id: %s", entityId);

    final Deferred<List<BUser>, BError, Void> deferred = new DeferredObject<>();

    if (StringUtils.isEmpty(entityId))
    {
        return deferred.reject(BError.getError(BError.Code.NULL, "Entity id is empty"));
    }

    final BUser user = DaoCore.fetchOrCreateEntityWithEntityID(BUser.class, entityId);

    DatabaseReference followersRef = FirebasePaths.userFollowsRef(entityId);

    followersRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            final List<BUser> followers = new ArrayList<BUser>();

            for (DataSnapshot snap : snapshot.getChildren())
            {
                String followingUserID = snap.getKey();

                if (StringUtils.isNotEmpty(followingUserID))
                {
                    BUser follwer = DaoCore.fetchOrCreateEntityWithEntityID(BUser.class, followingUserID);

                    FollowerLink f = user.fetchOrCreateFollower(follwer, FollowerLink.Type.FOLLOWS);

                    followers.add(follwer);
                }
            }

            Promise[] promises= new Promise[followers.size()];

            int count = 0;
            for (BUser u : followers)
            {
                promises[count] = BUserWrapper.initWithModel(u).once();

                count++;
            }

            MasterDeferredObject masterDeferredObject = new MasterDeferredObject(promises);

            masterDeferredObject.progress(new ProgressCallback<MasterProgress>() {
                @Override
                public void onProgress(MasterProgress masterProgress) {

                    if (DEBUG) Timber.d("MasterDeferredProgress, done: %s, failed: %s, total: %s", masterProgress.getDone(), masterProgress.getFail(), masterProgress.getTotal());

                    // Reject the promise if all promisses failed.
                    if (masterProgress.getFail() == masterProgress.getTotal())
                    {
                        deferred.reject(BError.getError(BError.Code.OPERATION_FAILED, "All promises failed"));
                    }
                    else
                        deferred.resolve(followers);
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
            deferred.reject(getFirebaseError(firebaseError));
        }
    });

    return deferred.promise();
}
 
開發者ID:MobileDev418,項目名稱:chat-sdk-android-push-firebase,代碼行數:72,代碼來源:BChatcatNetworkAdapter.java

示例14: pushForMessage

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
protected void pushForMessage(final BMessage message){
    if (!backendlessEnabled())
        return;

    if (DEBUG) Timber.v("pushForMessage");
    if (message.getThread().getTypeSafely() == BThread.Type.Private) {

        // Loading the message from firebase to get the timestamp from server.
        DatabaseReference firebase = FirebasePaths.threadRef(message.getThread().getEntityID())
                .child(BFirebaseDefines.Path.BMessagesPath)
                .child(message.getEntityID());

        firebase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                Long date = null;
                try {
                    date = (Long) snapshot.child(Keys.BDate).getValue();
                } catch (ClassCastException e) {
                    date = (((Double)snapshot.child(Keys.BDate).getValue()).longValue());
                }
                finally {
                    if (date != null)
                    {
                        message.setDate(new Date(date));
                        DaoCore.updateEntity(message);
                    }
                }

                // If we failed to get date dont push.
                if (message.getDate()==null)
                    return;

                BUser currentUser = currentUserModel();
                List<BUser> users = new ArrayList<BUser>();

                for (BUser user : message.getThread().getUsers())
                    if (!user.equals(currentUser))
                        if (!user.equals(currentUser)) {
                            // Timber.v(user.getEntityID() + ", " + user.getOnline().toString());
                            // sends push notification regardless of receiver online status
                            // TODO: add observer to online status
                            // if (user.getOnline() == null || !user.getOnline())
                            users.add(user);
                        }


                pushToUsers(message, users);
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {

            }
        });
    }
}
 
開發者ID:MobileDev418,項目名稱:chat-sdk-android-push-firebase,代碼行數:58,代碼來源:BFirebaseNetworkAdapter.java

示例15: loadCareTips

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private void loadCareTips(String species) {
    if (species != null) {
        DatabaseReference plantEntryReference = getDatabaseManager().getPlantEntryReference(species);
        plantEntryReference.addListenerForSingleValueEvent(new ValueEventListener() {
            /**
             * Read the data from the plant entry
             * @param dataSnapshot - the entry contents
             */
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                PlantEntry entry = dataSnapshot.getValue(PlantEntry.class);
                if (entry != null) {
                    mPlantGroup = entry.getGroup();
                    ((TextView) getActivity().findViewById(R.id.care_tips)).setText(entry.generateCareTips());
                    generateActiveGrowth(entry.getActive());
                    View toxicWarning = getActivity().findViewById(R.id.toxic_warning);
                    if (entry.isToxic()) {
                        toxicWarning.setVisibility(View.VISIBLE);
                    } else {
                        toxicWarning.setVisibility(View.GONE);
                    }
                    View noxiousWarning = getActivity().findViewById(R.id.noxious_warning);
                    List<String> noxious = entry.getNoxious();
                    if (noxious != null) {
                        noxiousWarning.setVisibility(View.VISIBLE);
                        TextView noxiousWarningTextView = getActivity().findViewById(R.id.noxious_warning_box);
                        if (noxious.contains("Noxious")) {
                            noxiousWarningTextView.setText(R.string.noxious_warning_msg);
                        }
                        if (noxious.contains("Quarantine")) {
                            noxiousWarningTextView.setText(String.format("%s \n\n%s", noxiousWarningTextView.getText(), getActivity().getString(R.string.quarantine_warning)));
                        }
                        if (noxious.contains("Regulated")) {
                            noxiousWarningTextView.setText(String.format("%s \n\n%s", noxiousWarningTextView.getText(), getActivity().getString(R.string.regulated_warning)));
                        }
                        if (noxious.contains("Banned")) {
                            noxiousWarningTextView.setText(String.format("%s \n\n%s", noxiousWarningTextView.getText(), getActivity().getString(R.string.banned_warning)));
                        }
                    }
                }
            }

            /**
             * Do nothing when cancelled
             * @param databaseError - ignored error
             */
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
}
 
開發者ID:iskandergaba,項目名稱:Botanist,代碼行數:53,代碼來源:PlantController.java


注:本文中的com.google.firebase.database.DatabaseReference.addListenerForSingleValueEvent方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。