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

项目:friendlypix-android    文件:PostsFragment.java   
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
        return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
                Post.class, R.layout.post_item, PostViewHolder.class, query) {
            @Override
            public void populateViewHolder(final PostViewHolder postViewHolder,
                                           final Post post, final int position) {
                setupPost(postViewHolder, post, position, null);
            }

            @Override
            public void onViewRecycled(PostViewHolder holder) {
                super.onViewRecycled(holder);
//                FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
            }
        };
    }
项目:firebase-admin-java    文件:KeepSyncedTestIT.java   
@Test
public void testDifferentIndependentQueries() throws Exception {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  Query query1 = ref.limitToFirst(1);
  Query query2 = ref.limitToFirst(2);

  query1.keepSynced(true);
  assertIsKeptSynced(query1);
  assertNotKeptSynced(query2);

  query2.keepSynced(true);
  assertIsKeptSynced(query1);
  assertIsKeptSynced(query2);

  query1.keepSynced(false);
  assertIsKeptSynced(query2);
  assertNotKeptSynced(query1);

  query2.keepSynced(false);
  assertNotKeptSynced(query1);
  assertNotKeptSynced(query2);
}
项目:GitHub    文件:FirebaseItemAdapter.java   
public FirebaseItemAdapter(Class<Item> modelClass, Query ref) {
    mModelClass = modelClass;
    mSnapshots = new FirebaseArray(ref);

    mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() {
        @Override
        public void onChanged(EventType type, int index, int oldIndex) {
            switch (type) {
                case Added:
                    notifyItemInserted(index);
                    break;
                case Changed:
                    notifyItemChanged(index);
                    break;
                case Removed:
                    notifyItemRemoved(index);
                    break;
                case Moved:
                    notifyItemMoved(oldIndex, index);
                    break;
                default:
                    throw new IllegalStateException("Incomplete case statement");
            }
        }
    });
}
项目: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) {

        }
    });
}
项目:MavsSnapUp    文件:MyItemsActivity.java   
private void loaditems() {
    Query query = mDatabase.orderByChild("createdBy").equalTo(mAuth.getCurrentUser().getUid());
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            items.clear();
            itemKey.clear();
            for(DataSnapshot snap : dataSnapshot.getChildren()) {
                if(snap.child("isItemSold").getValue(String.class)==null){
                    items.add(snap.child("itemName").getValue(String.class));
                    itemKey.add(snap.getKey());
                }
            }
            loadListView();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
项目:pracler    文件:UserManager.java   
public void getFollowingList(String userId, final OnCompleteGetUserFollowingListener listener)
{
    RemoteDatabaseManager rdm = new RemoteDatabaseManager();

    Query recentPostsQuery = rdm.getUsersReference().child(userId).child("following")
            .limitToFirst(3000);
    recentPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<String> arrayList = new ArrayList<String>();

            for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
                String name = (String) messageSnapshot.getKey();
                Log.e("UserManager", "Name : "+ name);
                arrayList.add(name);
            }

            listener.onComplete(arrayList);
            followingListCache = arrayList;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) { }
    });
}
项目:BuddyBook    文件:FirebaseDatabaseHelper.java   
public Query findBookSearch(String userId, String folderId) {
    if (folderId == null) {

        return mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo/searchField");

    } else {

        return mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(folderId)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo/searchField");

    }
}
项目:RxFBase    文件:RxFirebase.java   
@NonNull public static Observable<DataSnapshot> singleValue(final Query query) {
    return Observable.create(new Observable.OnSubscribe<DataSnapshot>() {
        @Override public void call(final Subscriber<? super DataSnapshot> subscriber) {
            final ValueEventListener valueEvent = query.addValueEventListener(new ValueEventListener() {
                @Override public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onNext(dataSnapshot);
                    }
                }
                @Override public void onCancelled(DatabaseError databaseError) {
                    subscriber.onError(databaseError.toException());
                }
            });
            subscriber.add(Subscriptions.create(new Action0() {
                @Override public void call() {
                    query.removeEventListener(valueEvent);
                }
            }));
        }
    });
}
项目:CSI-KJSCEOfficial    文件:MainActivity.java   
@Override
protected void onResume() {
    super.onResume();

    Query listenNewNotif = FirebaseDatabase
            .getInstance()
            .getReference(getString(R.string.firebase_key_last_notif))
            .child(getString(R.string.firebase_key_notif_id));
    listenNewNotif.keepSynced(true);
    final DatabaseHelper dbHelper = new DatabaseHelper(this);
    listenNewNotif.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(dbHelper.getUnreadCount()>0 && notifMenu!=null){
                notifMenu.setIcon(getResources().getDrawable(R.drawable.ic_notification_new));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG,databaseError.getMessage());
        }
    });
}
项目:EasyFirebase    文件:RxFirebaseHelper.java   
public <T> Observable<T> getObjects(final Query query, final Class<T> objectClass, final boolean useRootElement) {
    return Observable.create(new Observable.OnSubscribe<T>() {
        @Override
        public void call(final Subscriber<? super T> subscriber) {
            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(useRootElement) {
                        converter.convert(dataSnapshot, objectClass, subscriber);
                    } else {
                        for (DataSnapshot entry : dataSnapshot.getChildren()) {
                            converter.convert(entry, objectClass, subscriber);
                        }
                    }
                    subscriber.onCompleted();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });
}
项目:showcase-android    文件:RxFirebaseDatabase.java   
/**
 * Listener for a single change in te data at the given query location.
 *
 * @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
 * @return a {@link Maybe} which emits the actual state of the database for the given query.
 */
@NonNull
public static Maybe<DataSnapshot> observeSingleValueEvent(@NonNull final Query query) {
   return Maybe.create(new MaybeOnSubscribe<DataSnapshot>() {
      @Override
      public void subscribe(final MaybeEmitter<DataSnapshot> emitter) throws Exception {
         query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
               emitter.onSuccess(dataSnapshot);
               emitter.onComplete();
            }

            @Override
            public void onCancelled(DatabaseError error) {
               emitter.onError(new RxFirebaseDataException(error));
            }
         });
      }
   });
}
项目:Instincts-2k17    文件:RegisterActivity.java   
public void populateProfile() {
    nameEt.setText(currentUser.getDisplayName());
    emailEt.setText(currentUser.getEmail());

    Query userQuery = databaseReference.child("users").child(currentUser.getUid());
    userQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            try {
                User user = dataSnapshot.getValue(User.class);
                nameEt.setText(user.getName());
                emailEt.setText(user.getEmail());
                collegeEt.setText(user.getCollege());
                departmentEt.setText(user.getDepartment());
                yearEt.setText(String.valueOf(user.getYear()));
                mobileEt.setText(user.getMobile());
            } catch (Exception e) {
                Log.e("populateProfile", e.toString());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
项目:cat-is-a-dog    文件:RecentHabitEventHistoryDataSource.java   
/**
 * Creates a query for habit events from each user followed
 */
@Override
public void open() {
    recentEvents.clear();
    recentHabitEventMap.clear();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -7);
    long millis = cal.getTimeInMillis();

    for (String id : idList) {
        Query eventsQuery = FirebaseDatabase.getInstance().getReference("events/" + id)
                .orderByChild("eventDate").startAt(millis).endAt(DateTime.now().getMillis());
        eventsQuery.addChildEventListener(this);
        activeQueries.add(eventsQuery);
    }
}
项目:cat-is-a-dog    文件:CompletionMetricDataSource.java   
/**
 * Creates one query per week up to 4 weeks in the past
 */
@Override
public void open() {
    completionResultArray.clear();
    completionRates = new double[4];
    completionLatch = new CountDownLatch(4);

    if(habit.getSchedule().size() > 0) {
        for(Week week : DateUtil.GetNPastWeeks(DateTime.now(), 4)) {
            String startKey = HabitEventDataModel.habitStampKey(habit.getKey(), week.getStartOfWeek());
            String endKey = HabitEventDataModel.habitStampKey(habit.getKey(), week.getEndOfWeek());

            Query eventCountQuery = FirebaseDatabase.getInstance().getReference("events/" + habit.getUserId())
                    .orderByChild("habitStamp").startAt(startKey).endAt(endKey);

            eventCountQuery.addValueEventListener(this);
            queryRegister.add(eventCountQuery);
        }
    }
}
项目:social-app-android    文件:DatabaseHelper.java   
public void getPostListByUser(final OnDataChangedListener<Post> onDataChangedListener, String userId) {
    DatabaseReference databaseReference = database.getReference("posts");
    Query postsQuery;
    postsQuery = databaseReference.orderByChild("authorId").equalTo(userId);

    postsQuery.keepSynced(true);
    postsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            PostListResult result = parsePostList((Map<String, Object>) dataSnapshot.getValue());
            onDataChangedListener.onListChanged(result.getPosts());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getPostListByUser(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
项目:Wallpapers-Android-Clean-Architecture    文件:Comments.java   
private Observable<DataSnapshot> observe(final Query ref) {
    return Observable.create(emitter -> {
        final ValueEventListener listener =
                ref.addValueEventListener(new ValueEventListener() {
                    @Override public void onDataChange(DataSnapshot dataSnapshot) {
                        emitter.onNext(dataSnapshot);
                    }

                    @Override public void onCancelled(DatabaseError databaseError) {
                        emitter.onError(new FirebaseException(databaseError.getMessage()));
                    }
                });

        emitter.setCancellable(() -> ref.removeEventListener(listener));
    });
}
项目:react-native-firestack    文件:FirestackDatabase.java   
public void addValueEventListener(final String name, final ReadableArray modifiers) {
  final FirestackDBReference self = this;

  mValueListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      self.handleDatabaseEvent("value", mPath, dataSnapshot);
    }

    @Override
    public void onCancelled(DatabaseError error) {
      self.handleDatabaseError("value", mPath, error);
    }
  };

  Query ref = this.getDatabaseQueryAtPathAndModifiers(modifiers);
  ref.addValueEventListener(mValueListener);
  this.setListeningTo(mPath, "value");
}
项目:buddysearch    文件:FirebaseEntityStore.java   
private <T> Observable<T> getQuery(Query query, Action2<Subscriber<? super T>, DataSnapshot> onNextAction, boolean subscribeForSingleEvent) {
    return Observable.create(subscriber -> {
        ValueEventListener eventListener = new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                onNextAction.call(subscriber, dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                subscriber.onError(new FirebaseException(databaseError.getMessage()));
            }
        };
        if (subscribeForSingleEvent) {
            query.addListenerForSingleValueEvent(eventListener);
        } else {
            query.addValueEventListener(eventListener);
        }
        subscriber.add(Subscriptions.create(() -> query.removeEventListener(eventListener)));
    });
}
项目:SecretBrand    文件:RecentHighscoreFragment.java   
@Override
public Query getQuery(DatabaseReference databaseReference) {
    // [START recent_posts_query]
    // Last 100 posts, these are automatically the 100 most recent
    // due to sorting by push() keys
    Query recentPostsQuery;
    if (typeHighScore == 0) {
        recentPostsQuery = databaseReference.child("score_item")
                .limitToFirst(100);
    } else if (typeHighScore == 1) {
        recentPostsQuery = databaseReference.child("score_hero")
                .limitToFirst(100);
    } else {
        recentPostsQuery = databaseReference.child("score_random")
                .limitToFirst(100);
    }
    // [END recent_posts_query]

    return recentPostsQuery;
}
项目:Rx2Firebase    文件:RxFirebaseDatabase.java   
/**
 * Listener for a single change in te data at the given query location.
 *
 * @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
 * @return a {@link Maybe} which emits the actual state of the database for the given query. onSuccess will be only call when
 * the given {@link DataSnapshot} exists onComplete will only called when the data doesn't exist.
 */
@NonNull
public static Maybe<DataSnapshot> observeSingleValueEvent(@NonNull final Query query) {
   return Maybe.create(new MaybeOnSubscribe<DataSnapshot>() {
      @Override
      public void subscribe(final MaybeEmitter<DataSnapshot> emitter) throws Exception {
         query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
               if (dataSnapshot.exists()) {
                  emitter.onSuccess(dataSnapshot);
               }
               else {
                 emitter.onComplete();
               }
            }

            @Override
            public void onCancelled(DatabaseError error) {
               emitter.onError(new RxFirebaseDataException(error));
            }
         });
      }
   });
}
项目:BookJobs    文件:BookController.java   
private void updateOwnerCollection(final String BookReference) {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    Query query = mCurrentUser.orderByChild("email").equalTo(user.getEmail());

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = dataSnapshot.getValue().toString();
            String userRef = value.substring(1, value.indexOf('='));
            dataSnapshot.child(userRef).child("owns").child(bookRef).getRef().setValue(1);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e(TAG, "Failed to reach the server");
        }
    });
}
项目:delern    文件:EditCardListActivity.java   
private CardRecyclerViewAdapter createAdapter(@Nullable final Query query) {
    // Before creating new Adapter, check whether we have previous one.
    // If Adapter already exists, unregister DataObserver and clean listener.
    cleanup();

    if (query == null) {
        mFirebaseAdapter = new CardRecyclerViewAdapter(mPresenter.getDeck(),
                mPresenter.getQuery(), this);
    } else {
        mFirebaseAdapter = new CardRecyclerViewAdapter(mPresenter.getDeck(), query, this);
    }
    mFirebaseAdapter.startListening();

    // If it was got 0 cards, AdapterDataObserver won't run. Therefore it will be shown
    // the previous value.
    mNumberOfCards.setText(String.format(getString(R.string.number_of_cards),
            mFirebaseAdapter.getItemCount()));
    mFirebaseAdapter.registerAdapterDataObserver(mFirebaseAdapterDataObserver);
    return mFirebaseAdapter;
}
项目:Android-Clean-Architecture    文件:Comments.java   
private Observable<DataSnapshot> observe(final Query ref) {
    return Observable.create(new Observable.OnSubscribe<DataSnapshot>() {
        @Override
        public void call(final Subscriber<? super DataSnapshot> subscriber) {
            final ValueEventListener listener = ref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    subscriber.onNext(dataSnapshot);
                }

                @Override public void onCancelled(DatabaseError databaseError) {
                    subscriber.onError(new FirebaseException(databaseError.getMessage()));
                }
            });

            // When the subscription is cancelled, remove the listener
            subscriber.add(Subscriptions.create(new Action0() {
                @Override
                public void call() {
                    ref.removeEventListener(listener);
                }
            }));
        }
    });
}
项目:Attendance    文件:AllEmpsAbsDataModel.java   
@NonNull
@Override
public Observable<List<Attendance>> getObservableAbsencesFromFB(@NonNull final String umex, @NonNull final String usicox) {

    //get absences for ico and umex

    //injected
    //Query usersQuery = mFirebaseDatabase.child("company-absences").child(usicox).orderByChild("ume").equalTo(umex);
    Query usersQuery = mFirebaseDatabase.child("company-absences").child(usicox).orderByChild("ume").equalTo(umex);

    return RxFirebaseDatabase.getInstance().observeValueEvent(usersQuery)
            .flatMap(dataSnapshot ->{
                List<Attendance> blogPostEntities = new ArrayList<>();
                for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                    String keys = childDataSnapshot.getKey();
                    //System.out.println("keys " + keys);
                    Attendance resultx = childDataSnapshot.getValue(Attendance.class);
                    resultx.setRok(keys);
                    blogPostEntities.add(resultx);
                }
                return Observable.just(blogPostEntities);
            });

}
项目:Attendance    文件:DataModel.java   
@NonNull
@Override
public Observable<List<Employee>> getObservableFBusersEmployee() {
final DatabaseReference firebaseRef = FirebaseDatabase.getInstance().getReference();
Query usersQuery = firebaseRef.child("users");

return RxFirebaseDatabase.getInstance().observeValueEvent(usersQuery)
        .flatMap(dataSnapshot ->{
            List<Employee> blogPostEntities = new ArrayList<>();
        for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
            String keys = childDataSnapshot.getKey();
            //System.out.println("keys " + keys);
            Employee resultx = childDataSnapshot.getValue(Employee.class);
            resultx.setKeyf(keys);
            blogPostEntities.add(resultx);
        }
         return Observable.just(blogPostEntities);
});

}
项目:Attendance    文件:DgAllEmpsAbsDataModel.java   
@NonNull
@Override
public Observable<List<Employee>> getObservableFBusersEmployee(String usicox) {

    Query usersQuery = mFirebaseDatabase.child("users").orderByChild("usico").equalTo(usicox);

    return RxFirebaseDatabase.getInstance().observeValueEvent(usersQuery)
            .flatMap(dataSnapshot ->{
                List<Employee> blogPostEntities = new ArrayList<>();
                for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                    String keys = childDataSnapshot.getKey();
                    //System.out.println("keys " + keys);
                    Employee resultx = childDataSnapshot.getValue(Employee.class);
                    resultx.setKeyf(keys);
                    blogPostEntities.add(resultx);
                }
                return Observable.just(blogPostEntities);
            });

}
项目:Attendance    文件:EmployeeDataModel.java   
@NonNull
@Override
public Observable<List<Employee>> getObservableFBusersEmployee() {
final DatabaseReference firebaseRef = FirebaseDatabase.getInstance().getReference();
Query usersQuery = firebaseRef.child("users");

return RxFirebaseDatabase.getInstance().observeValueEvent(usersQuery)
        .flatMap(dataSnapshot ->{
            List<Employee> blogPostEntities = new ArrayList<>();
        for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
            String keys = childDataSnapshot.getKey();
            //System.out.println("keys " + keys);
            Employee resultx = childDataSnapshot.getValue(Employee.class);
            resultx.setKeyf(keys);
            blogPostEntities.add(resultx);
        }
         return Observable.just(blogPostEntities);
});

}
项目:react-native-firestack    文件:FirestackDatabase.java   
public void addOnceValueEventListener(final ReadableArray modifiers,
                                      final Callback callback) {
  final FirestackDBReference self = this;

  mOnceValueListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      WritableMap data = FirestackUtils.dataSnapshotToMap("value", mPath, dataSnapshot);
      callback.invoke(null, data);
    }

    @Override
    public void onCancelled(DatabaseError error) {
      WritableMap err = Arguments.createMap();
      err.putInt("errorCode", error.getCode());
      err.putString("errorDetails", error.getDetails());
      err.putString("description", error.getMessage());
      callback.invoke(err);
    }
  };

  Query ref = this.getDatabaseQueryAtPathAndModifiers(modifiers);
  ref.addListenerForSingleValueEvent(mOnceValueListener);
}
项目:firebase-admin-java    文件:OrderByTestIT.java   
@Test
public void testQueriesOnLeafNodes()
    throws InterruptedException, ExecutionException, TestFailure, TimeoutException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;
  final Semaphore semaphore = new Semaphore(0);
  new WriteFuture(ref, "leaf-node").timedGet();

  final List<DataSnapshot> snapshots = new ArrayList<>();
  Query query = ref.orderByChild("foo").limitToLast(1);
  final ValueEventListener listener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              snapshots.add(snapshot);
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);

  Assert.assertEquals(1, snapshots.size());
  Assert.assertNull(snapshots.get(0).getValue());

  // cleanup
  TestHelpers.waitForRoundtrip(ref);
  ref.removeEventListener(listener);
}
项目:firebase-admin-java    文件:OrderByTestIT.java   
@Test
public void testServerRespectsKeyIndex()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference writer = refs.get(0);
  DatabaseReference reader = refs.get(1);

  Map<String, Object> initial = MapBuilder.of("a", 1, "b", 2, "c", 3);
  // If the server doesn't respect the index, it will send down limited data, but with no
  // offset, so the expected and actual data don't match.
  Query query = reader.orderByKey().startAt("b").limitToFirst(2);

  new WriteFuture(writer, initial).timedGet();

  final List<String> actualChildren = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener valueListener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              for (DataSnapshot child : snapshot.getChildren()) {
                actualChildren.add(child.getKey());
              }
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);
  Assert.assertEquals(ImmutableList.of("b", "c"), actualChildren);

  // cleanup
  reader.removeEventListener(valueListener);
}
项目:firebase-admin-java    文件:ReadFuture.java   
private ReadFuture(
    final Query ref, final CompletionCondition condition, final boolean ignoreFirstNull) {
  semaphore = new Semaphore(0);
  this.valueEventListener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          if (ignoreFirstNull && events.size() == 0 && snapshot.getValue() == null) {
            return;
          }
          events.add(new EventRecord(snapshot, Event.EventType.VALUE, null));
          try {
            if (condition.isComplete(events)) {
              ref.removeEventListener(valueEventListener);
              finish();
            }
          } catch (Exception e) {
            exception = e;
            finish();
          }
        }

        @Override
        public void onCancelled(DatabaseError error) {
          wasCancelled = true;
          finish();
        }
      };
  ref.addValueEventListener(this.valueEventListener);
}
项目:firebase-admin-java    文件:ReadFuture.java   
public ReadFuture(final Query ref) {
  this(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          return true;
        }
      });
}
项目:firebase-admin-java    文件:ReadFuture.java   
public static ReadFuture untilNonNull(Query ref) {
  return new ReadFuture(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          return events.get(events.size() - 1).getSnapshot().getValue() != null;
        }
      });
}
项目:firebase-admin-java    文件:ReadFuture.java   
public static ReadFuture untilEquals(Query ref, final Object value, boolean ignoreFirstNull) {
  return new ReadFuture(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          Object eventValue = events.get(events.size() - 1).getSnapshot().getValue();
          return eventValue != null && eventValue.equals(value);
        }
      },
      ignoreFirstNull);
}
项目:firebase-admin-java    文件:ReadFuture.java   
public static ReadFuture untilCountAfterNull(Query ref, final int count) {
  return new ReadFuture(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          return events.size() == count;
        }
      },
      true);
}
项目:firebase-admin-java    文件:ReadFuture.java   
public static ReadFuture untilCount(Query ref, final int count) {
  return new ReadFuture(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          return events.size() == count;
        }
      });
}
项目:firebase-admin-java    文件:KeepSyncedTestIT.java   
@Test
public void testKeepSyncedAffectOnQueries() throws Exception {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  ref.keepSynced(true);
  Query query = ref.limitToFirst(5);
  query.keepSynced(true);
  assertIsKeptSynced(ref);

  ref.keepSynced(false);
  assertNotKeptSynced(ref);
  // currently, setting false on the default query affects all queries at that location
  assertNotKeptSynced(query);
}
项目:firebase-admin-java    文件:KeepSyncedTestIT.java   
private void assertIsKeptSynced(Query query) throws Exception {
  DatabaseReference ref = query.getRef();

  // First set a unique value to the value of a child.
  long counter = globalKeepSyncedTestCounter++;
  final Map<String, Object> value = ImmutableMap.<String, Object>of("child", counter);
  new WriteFuture(ref, value).timedGet();

  // Next go offline, if it's kept synced we should have kept the value.
  // After going offline no way to get the value except from cache.
  ref.getDatabase().goOffline();

  try {
    new ReadFuture(
        query,
        new ReadFuture.CompletionCondition() {
          @Override
          public boolean isComplete(List<EventRecord> events) {
            assertEquals(1, events.size());
            assertEquals(value, events.get(0).getSnapshot().getValue());
            return true;
          }
        })
        .timedGet();
  } finally {
    // All good, go back online
    ref.getDatabase().goOnline();
  }
}
项目:firebase-admin-java    文件:KeepSyncedTestIT.java   
private void assertNotKeptSynced(Query query) throws Exception {
  DatabaseReference ref = query.getRef();

  // First set a unique value to the value of a child.
  long current = globalKeepSyncedTestCounter++;
  final Map<String, Object> oldValue = ImmutableMap.<String, Object>of("child", current);

  long next = globalKeepSyncedTestCounter++;
  final Map<String, Object> nextValue = ImmutableMap.<String, Object>of("child", next);

  new WriteFuture(ref, oldValue).timedGet();

  // Next go offline, if it's kept synced we should have kept the value and we'll get an even
  // with the *old* value.
  ref.getDatabase().goOffline();

  try {
    ReadFuture readFuture =
        new ReadFuture(query, new ReadFuture.CompletionCondition() {
            @Override
            public boolean isComplete(List<EventRecord> events) {
              // We expect this to get called with the next value, not the old value.
              assertEquals(1, events.size());
              assertEquals(nextValue, events.get(0).getSnapshot().getValue());
              return true;
            }
          });

    // By now, if we had it synced we should have gotten an event with the wrong value
    // Write a new value so the value event listener will be triggered
    ref.setValueAsync(nextValue);
    readFuture.timedGet();
  } finally {
    // All good, go back online
    ref.getDatabase().goOnline();
  }
}
项目:Quadro    文件:RecentPostsFragment.java   
@Override
public Query getQuery(DatabaseReference databaseReference) {
    // [START recent_posts_query]
    // Last 100 posts, these are automatically the 100 most recent
    // due to sorting by push() keys
    Query recentPostsQuery = databaseReference.child("posts")
            .limitToFirst(100);
    // [END recent_posts_query]

    return recentPostsQuery;
}