本文整理汇总了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) {
}
});
}
示例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());
}
});
}
示例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) {
}
});
}
示例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) {
}
});
}
示例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) {
}
});
}
示例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();
}
示例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);
}
示例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;
}
示例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();
}
});
}
示例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();
}
});
}
示例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);
}
示例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) {
}
});
}
示例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();
}
示例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) {
}
});
}
}
示例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) {
}
});
}
}