com.google.firebase.database.DataSnapshot Java Examples

The following examples show how to use com.google.firebase.database.DataSnapshot. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FirebaseCache.java    From white-label-event-app with Apache License 2.0 6 votes vote down vote up
private void warmEvent() {
    final DatabaseReference eventRef = fdb.getReference("/event");
    eventRef.addValueEventListener(new ExecutorValueEventListener(executor) {
        @Override
        protected void onDataChangeExecutor(DataSnapshot data) {
            LOGGER.fine("New Event data");
            event = FirebaseDatabaseHelpers.toEvent(data);
            bus.post(event);
        }

        @Override
        protected void onCancelledExecutor(DatabaseError databaseError) {
            LOGGER.log(Level.SEVERE, "Error reading event", databaseError.toException());
        }
    });
}
 
Example #2
Source File: Home.java    From UberClone with MIT License 6 votes vote down vote up
private void displayLocation(){
    if (currentLat!=null && currentLng!=null){
        //presence system
        driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
        driversAvailable.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //if have change from drivers table, we will reload all drivers available
                loadAllAvailableDriver(new LatLng(currentLat, currentLng));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        loadAllAvailableDriver(new LatLng(currentLat, currentLng));

    }else{
        Message.messageError(this, Errors.WITHOUT_LOCATION);
    }

}
 
Example #3
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> single(@NonNull final Query query) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            final ValueEventListener listener = listener(emit);

            emit.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    query.removeEventListener(listener);
                }
            });

            query.addListenerForSingleValueEvent(listener);
        }
    });
}
 
Example #4
Source File: Helper.java    From VitonBet with MIT License 6 votes vote down vote up
public static void SetUsername(final AppCompatActivity a) {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {

            DatabaseReference db = FirebaseDatabase.getInstance().getReference()
                    .child("Users").child(user.getUid().toString()).child("username");

            db.addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    TextView bal = (TextView)a.findViewById(R.id.username);
                    bal.setText("Welcome: " + dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                    // ...
                }
            });
        }
    }
 
Example #5
Source File: BasketFragment.java    From RestaurantApp with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        productBasket = new ProductBasket();
        productBasket.setPiece(snapshot.getValue(ProductBasket.class).getPiece());
        productBasket.setProductId(snapshot.getValue(ProductBasket.class).getProductId());
        productBaskets.add(productBasket);
    }

    try {
        Toast.makeText(getActivity(), productBaskets.size()+"", Toast.LENGTH_SHORT).show();
    }catch (Exception e){

    }

}
 
Example #6
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetWithPriority()
    throws ExecutionException, TimeoutException, InterruptedException, TestFailure {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference ref1 = refs.get(0);
  final DatabaseReference ref2 = refs.get(1);

  ReadFuture readFuture = ReadFuture.untilNonNull(ref1);

  new WriteFuture(ref1, "hello", 5).timedGet();
  List<EventRecord> result = readFuture.timedGet();
  DataSnapshot snap = result.get(result.size() - 1).getSnapshot();
  assertEquals(5.0, snap.getPriority());
  assertEquals("hello", snap.getValue());

  result = ReadFuture.untilNonNull(ref2).timedGet();
  snap = result.get(result.size() - 1).getSnapshot();
  assertEquals(5.0, snap.getPriority());
  assertEquals("hello", snap.getValue());
}
 
Example #7
Source File: RxFirebaseDatabase.java    From RxFirebase with Apache License 2.0 6 votes vote down vote up
@NonNull
public static Observable<DataSnapshot> observeSingleValueEvent(@NonNull final Query query) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<DataSnapshot>() {
        @Override
        public void call(final Subscriber<? super DataSnapshot> subscriber) {
            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onNext(dataSnapshot);
                        subscriber.onCompleted();
                    }
                }

                @Override
                public void onCancelled(DatabaseError error) {
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onError(new RxFirebaseDataException(error));
                    }
                }
            });
        }
    });
}
 
Example #8
Source File: SignUp.java    From Walk-In-Clinic-Android-App with MIT License 6 votes vote down vote up
public void updateServices(){
    databaseServices.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            services.clear();  // might need to remove
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                DataBaseService service = postSnapshot.getValue(DataBaseService.class);
                services.add(service);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
 
Example #9
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void updateProfileLikeCountAfterRemovingPost(Post post) {
    DatabaseReference profileRef = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY + "/" + post.getAuthorId() + "/likesCount");
    final long likesByPostCount = post.getLikesCount();

    profileRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= likesByPostCount) {
                mutableData.setValue(currentValue - likesByPostCount);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating likes count transaction is completed.");
        }
    });

}
 
Example #10
Source File: Helper.java    From VitonBet with MIT License 6 votes vote down vote up
public static void SetDOB(final AppCompatActivity a) {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {

            DatabaseReference db = FirebaseDatabase.getInstance().getReference()
                    .child("Users").child(user.getUid().toString()).child("dob");

            db.addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    TextView bal = (TextView)a.findViewById(R.id.dobfield);
                    bal.setText("Date of Birth: " + dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                    // ...
                }
            });
        }
    }
 
Example #11
Source File: MainActivity.java    From Simple-Blog-App with MIT License 6 votes vote down vote up
public void setLikeBtn(final String post_key) {
    mDatabaseLike.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
                mLikebtn.setImageResource(R.drawable.ic_yes_heart_colored);
            } else {
                mLikebtn.setImageResource(R.drawable.ic_no_heart_gray);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
 
Example #12
Source File: RxFirebaseDatabaseTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testData_DataReference() {
    TestObserver<DataSnapshot> sub = TestObserver.create();

    RxFirebaseDatabase.data(mockDatabaseReference)
            .subscribe(sub);

    verifyDataReferenceAddListenerForSingleValueEvent();
    callValueEventOnDataChange("Foo");
    sub.dispose();

    // Ensure no more values are emitted after unsubscribe
    callValueEventOnDataChange("Foo");

    sub.assertNoErrors();
    sub.assertComplete();
    sub.assertValueCount(1);
}
 
Example #13
Source File: FollowInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getFollowersList(String targetUserId, OnDataChangedListener<String> onDataChangedListener) {
    getFollowersRef(targetUserId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> list = new ArrayList<>();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Follower follower = snapshot.getValue(Follower.class);

                if (follower != null) {
                    String profileId = follower.getProfileId();
                    list.add(profileId);
                }

            }
            onDataChangedListener.onListChanged(list);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logDebug(TAG, "getFollowersList, onCancelled");
        }
    });
}
 
Example #14
Source File: TripHistory.java    From UberClone with MIT License 6 votes vote down vote up
private void getHistory(){
    riderHistory.child(Common.userID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
                History history = postSnapshot.getValue(History.class);
                listData.add(history);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}
 
Example #15
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: FavouriteProductFragment.java    From FaceT with Mozilla Public License 2.0 6 votes vote down vote up
private void checkUserExist() {

        if (mAuth.getCurrentUser() != null) {
            final String user_id = mAuth.getCurrentUser().getUid();

            mDatabaseUsers.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!dataSnapshot.hasChild(user_id)) {
                        Intent mainIntent = new Intent(getActivity(), ProfileEditActivity.class);
                        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(mainIntent);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }
 
Example #17
Source File: RxDatabaseReferenceTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testData_DataReference() {
    TestObserver<DataSnapshot> sub = TestObserver.create();

    RxDatabaseReference.single(mockDatabaseReference)
            .subscribe(sub);

    verifyDataReferenceAddListenerForSingleValueEvent();
    callValueEventOnDataChange("Foo");
    sub.dispose();

    // Ensure no more values are emitted after unsubscribe
    callValueEventOnDataChange("Foo");

    sub.assertNoErrors();
    sub.assertComplete();
    sub.assertValueCount(1);
}
 
Example #18
Source File: OrderManager.java    From Pharmacy-Android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetch order by order address key
 * @param key
 * @return Order
 */
public static Observable<Order> fetchOrderByKey(String key) {
    return Observable.create(subscriber -> {
        FirebaseDatabase.getInstance().getReference(Constants.Path.ORDERS).child(key).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                try {
                    Order order = dataSnapshot.getValue(Order.class);
                    subscriber.onNext(order);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    Timber.e(e, "Order retrival by key failed, key: %s", key);
                    subscriber.onError(e);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Timber.e(databaseError.toException(), "Order retrival by key failed, key: %s", key);
                subscriber.onError(databaseError.toException());
            }
        });

    });
}
 
Example #19
Source File: RxFirebaseHelper.java    From EasyFirebase with Apache License 2.0 6 votes vote down vote up
public <T> Observable<T> push(final DatabaseReference databaseReference) {
    final Observable<T> observable = Observable.create(new Observable.OnSubscribe<T>() {
                                                           @Override
                                                           public void call(final Subscriber<? super T> subscriber) {
                                                               databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                                                                   @Override
                                                                   public void onDataChange(DataSnapshot dataSnapshot) {
                                                                       subscriber.onNext(null);
                                                                       subscriber.onCompleted();
                                                                   }

                                                                   @Override
                                                                   public void onCancelled(DatabaseError databaseError) {

                                                                   }
                                                               });
                                                           }
                                                       });

    databaseReference.push();
    return observable;
}
 
Example #20
Source File: ResolverDataSnapshotList.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static List resolve(DataSnapshot dataSnapshot) {
    if (dataSnapshot.getValue() == null) {
        throw new IllegalStateException();
    }
    List result = new ArrayList<>();
    Iterable<DataSnapshot> dataSnapshots;
    if (ClassReflection.isAssignableFrom(Map.class, dataSnapshot.getValue().getClass())) {
        dataSnapshots = ((Map) dataSnapshot.getValue()).values();
    } else {
        dataSnapshots = dataSnapshot.getChildren();
    }
    for (Object o : dataSnapshots) {
        if (o instanceof DataSnapshot) {
            result.add(((DataSnapshot) o).getValue());
        } else {
            result.add(o);
        }
    }
    return result;
}
 
Example #21
Source File: ChatFragment.java    From SnapchatClone with MIT License 6 votes vote down vote up
private void listenForData() {
    DatabaseReference receiveDB = FirebaseDatabase.getInstance().getReference().child("users")
            .child(FirebaseAuth.getInstance().getUid()).child("received");

    receiveDB.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot snap : dataSnapshot.getChildren()) {
                    getUserInfo(snap.getKey());
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
 
Example #22
Source File: FirebaseHelper.java    From UberClone with MIT License 6 votes vote down vote up
public void registerByGoogleAccount(final GoogleSignInAccount account){
    final User user=new User();
    users.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User post = dataSnapshot.child(account.getId()).getValue(User.class);

            if(post==null) showRegisterPhone(user, account);
            else loginSuccess();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
 
Example #23
Source File: FirebaseDatabaseHelpers.java    From white-label-event-app with Apache License 2.0 6 votes vote down vote up
public static AgendaSection toAgendaSection(final DataSnapshot data) {
    final AgendaSection section = new AgendaSection();
    populateSection(data, section);
    Map<String, AgendaItem> items = data.child("items").getValue(new GenericTypeIndicator<Map<String, AgendaItem>>() {});
    if (items == null) {
        items = Collections.emptyMap();
    }

    // Force empty speaker list when null so the client doesn't have to
    // always check null.
    for (final Map.Entry<String, AgendaItem> entry : items.entrySet()) {
        if (entry.getValue().getSpeakerIds() == null) {
            entry.getValue().setSpeakerIds(Collections.<String>emptyList());
        }
    }

    section.setItems(items);
    return section;
}
 
Example #24
Source File: HomeBaseFragment.java    From kute with Apache License 2.0 6 votes vote down vote up
/********************************* Data Querying Methods *************************/
//Load friends from firebase
public void getFirebaseFriend() {
    /******************** Getting Friends From Firebase *************/
    String ref = "Friends/" + getActivity().getSharedPreferences("user_credentials", 0).getString("Name", null);
    Log.d(TAG, "Firebase Reference :" + ref);
    DatabaseReference friends = FirebaseDatabase.getInstance().getReference(ref);
    friends.keepSynced(true);
    friends.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot k : dataSnapshot.getChildren()) {
                friend_list.add(k.getKey());
                Log.d(TAG, "Debug Firebase data query" + k.getValue().toString());
            }
            
            Log.d(TAG, String.format("The Friend List Size is %d",friend_list.size()));
            getFirstFriendProfile();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example #25
Source File: FollowInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getFollowingPosts(String userId, OnDataChangedListener<FollowingPost> listener) {
    databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.FOLLOWINGS_POSTS_DB_KEY)
            .child(userId)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    List<FollowingPost> list = new ArrayList<>();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        FollowingPost followingPost = snapshot.getValue(FollowingPost.class);
                        list.add(followingPost);
                    }

                    Collections.reverse(list);

                    listener.onListChanged(list);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    LogUtil.logDebug(TAG, "getFollowingPosts, onCancelled");
                }
            });
}
 
Example #26
Source File: firebaseutils.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
public static void setbio(final TextView bio){
    FirebaseAuth auth=FirebaseAuth.getInstance();
    FirebaseUser user=auth.getCurrentUser();
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    if (user !=null){
        DatabaseReference myRef = database.getReference("users").child(user.getUid()).child("user_bio");

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    bio.setText(dataSnapshot.getValue(String.class));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}
 
Example #27
Source File: MakeupProductFragment.java    From FaceT with Mozilla Public License 2.0 6 votes vote down vote up
public void getDatabaseProductData() {
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Product");
    mDatabase.keepSynced(true);
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                if (ds.getKey().equals(selectedFoundationID) || ds.getKey().equals(selectedBrushID) || ds.getKey().equals(selectedEyeshadowID) || ds.getKey().equals(selectedLipstickID)) {
                    ProductTypeTwo result = ds.getValue(ProductTypeTwo.class);
                    mAppliedProducts.put(ds.getKey(), result);
                    Log.d(" product key ", ds.getKey());
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }

    });
}
 
Example #28
Source File: FirebaseDataManager.java    From Android-MVP-vs-MVVM-Samples with Apache License 2.0 6 votes vote down vote up
public final void getCheckInByEmail(final String _email, final OnLoadCallback<CheckIn> loadCallback) {

        mDatabaseCheckIn.orderByChild("email").equalTo(_email).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long count = dataSnapshot.getChildrenCount();
                Log.d(TAG, TABLE_CHECK_IN + " | MyCheckIns | Count is: " + count);
                final List<CheckIn> checkIns = new ArrayList<CheckIn>();
                for (final DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    final CheckIn checkIn = dataSnapshot1.getValue(CheckIn.class);
                    checkIns.add(checkIn);
                    Log.d(TAG, TABLE_CHECK_IN + " | MyCheckIns | Value " + checkIn.checkInMessage);
                }
                loadCallback.onDataChange(checkIns);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, TABLE_CHECK_IN + " | MyCheckIns | Failed to read: ", databaseError.toException());
                loadCallback.onCancelled();
            }
        });

    }
 
Example #29
Source File: FirebaseDatabaseHelper.java    From Duolingo-Clone with MIT License 5 votes vote down vote up
@Override
public void getLessonCompleted() {

    if (Injection.providesAuthHelper().getAuthInstance().getCurrentUser() != null) {

        String userID = Injection.providesAuthHelper().getAuthInstance().getCurrentUser().getUid();

        String language = Hawk.get("currentLanguage");

        myRef.child("user")
                .child(userID)
                .child("course")
                .child(language)
                .child("lessons")
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        for (DataSnapshot ds : dataSnapshot.getChildren()) {

                            Hawk.put(ds.getKey().toString(), ds.getValue());
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
    }
}
 
Example #30
Source File: FirestackUtils.java    From react-native-firestack with MIT License 5 votes vote down vote up
public static WritableArray getChildKeys(DataSnapshot snapshot) {
  WritableArray childKeys = Arguments.createArray();

  if (snapshot.hasChildren()) {
    for (DataSnapshot child : snapshot.getChildren()) {
      childKeys.pushString(child.getKey());
    }
  }

  return childKeys;
}