com.google.firebase.database.Query Java Examples

The following examples show how to use com.google.firebase.database.Query. 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: ResolverQueryOrderBy.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Override
public Query resolve(OrderByClause orderByClause, Query target) {
    switch (orderByClause.getOrderByMode()) {
        case ORDER_BY_CHILD:
            if (orderByClause.getArgument() == null) {
                throw new IllegalArgumentException(MISSING_ARGUMENT);
            }
            return target.orderByChild(orderByClause.getArgument());
        case ORDER_BY_KEY:
            return target.orderByKey();
        case ORDER_BY_VALUE:
            return target.orderByValue();
        default:
            throw new IllegalStateException();
    }
}
 
Example #2
Source File: KeepSyncedTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
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 = new MapBuilder().put("child", counter).build();
  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();

  new ReadFuture(
          query,
          (List<EventRecord> events) -> {
            assertEquals(1, events.size());
            assertEquals(value, events.get(0).getSnapshot().getValue());
            return true;
          })
      .timedGet();

  // All good, go back online
  ref.getDatabase().goOnline();
}
 
Example #3
Source File: GeoQuery.java    From geofire-android with Apache License 2.0 6 votes vote down vote up
private void addValueToReadyListener(final Query firebase, final GeoHashQuery query) {
    firebase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            synchronized (GeoQuery.this) {
                GeoQuery.this.outstandingQueries.remove(query);
                GeoQuery.this.checkAndFireReady();
            }
        }

        @Override
        public void onCancelled(@NonNull final DatabaseError databaseError) {
            synchronized (GeoQuery.this) {
                for (final GeoQueryDataEventListener listener : GeoQuery.this.eventListeners) {
                    GeoQuery.this.geoFire.raiseEvent(new Runnable() {
                        @Override
                        public void run() {
                            listener.onGeoQueryError(databaseError);
                        }
                    });
                }
            }
        }
    });
}
 
Example #4
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getPostListByUser(final OnDataChangedListener<Post> onDataChangedListener, String userId) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY);
    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()));
        }
    });
}
 
Example #5
Source File: QueryActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void basicQueryValueListener() {
    String myUserId = getUid();
    Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
            .orderByChild("starCount");

    // [START basic_query_value_listener]
    // My top posts by number of stars
    myTopPostsQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                // TODO: handle the post
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            // ...
        }
    });
    // [END basic_query_value_listener]
}
 
Example #6
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 #7
Source File: FirebaseQueryLiveDataElement.java    From budgetto with MIT License 6 votes vote down vote up
public FirebaseQueryLiveDataElement(Class<T> genericTypeClass, Query query) {
    setValue(null);
    listener = new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            T item = dataSnapshot.getValue(genericTypeClass);
            setValue(new FirebaseElement<>(item));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            setValue(new FirebaseElement<>(databaseError));
            removeListener();
            setListener();
        }
    };
    this.query = query;
}
 
Example #8
Source File: FirestackDatabase.java    From react-native-firestack with MIT License 6 votes vote down vote up
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");
}
 
Example #9
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getPostListByUser(final OnDataChangedListener<Post> onDataChangedListener, String userId) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY);
    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()));
        }
    });
}
 
Example #10
Source File: detailActivity.java    From Doctorave with MIT License 6 votes vote down vote up
public void deleteFromFirebase(final String id){
    Query hekkQuery = mDatabaseReference;

    hekkQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            dataSnapshot.child(id).getRef().removeValue()
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            deletePhotoFromStorage(id);
                        }
                    });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

    /////this is for firebase storage
    Task<Void> task = mStorageReference.child(String.valueOf(id).concat("_Image")).delete();
}
 
Example #11
Source File: patientsFragment.java    From Doctorave with MIT License 6 votes vote down vote up
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
    adapter.swapCursor(data);

    if(data.getCount() == 0){
        Query hekkQuery = mDatabaseReference;

        hekkQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(doctorPreference.getWantToRestoreData(getActivity())){
                    if(dataSnapshot.getChildrenCount() == 0){

                    }else {
                        showAlertToRestoreData(dataSnapshot.getChildrenCount());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
}
 
Example #12
Source File: GeoQuery.java    From geofire-java with MIT License 6 votes vote down vote up
private void addValueToReadyListener(final Query firebase, final GeoHashQuery query) {
    firebase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            synchronized (GeoQuery.this) {
                GeoQuery.this.outstandingQueries.remove(query);
                GeoQuery.this.checkAndFireReady();
            }
        }

        @Override
        public void onCancelled(final DatabaseError databaseError) {
            synchronized (GeoQuery.this) {
                for (final GeoQueryDataEventListener listener : GeoQuery.this.eventListeners) {
                    GeoQuery.this.geoFire.raiseEvent(new Runnable() {
                        @Override
                        public void run() {
                            listener.onGeoQueryError(databaseError);
                        }
                    });
                }
            }
        }
    });
}
 
Example #13
Source File: ProviderQueryFilteringTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void applyFiltering1() {
    // Given
    ProviderQueryFiltering provider = new ProviderQueryFiltering();
    OrderByClause orderByClause = new OrderByClause(OrderByMode.ORDER_BY_KEY, "test");
    Array<Filter> filters = new Array<>(new Filter[]{new Filter(FilterType.LIMIT_FIRST, 2)});
    Query query = Mockito.mock(Query.class);
    Mockito.when(query.limitToFirst(Mockito.anyInt())).thenReturn(query);
    Mockito.when(query.orderByKey()).thenReturn(query);
    provider.setQuery(query);
    provider.setFilters(filters);
    provider.setOrderByClause(orderByClause);

    // When
    Object result = provider.applyFiltering();

    // Then
    Assert.assertNotNull(result);
}
 
Example #14
Source File: RxValue.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 #15
Source File: PostsFragment.java    From friendlypix-android with Apache License 2.0 6 votes vote down vote up
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
    FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>()
            .setLifecycleOwner(this)
            .setQuery(query, Post.class)
            .build();

    return new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull PostViewHolder postViewHolder,
                                        int position,
                                        @NonNull Post post) {
            setupPost(postViewHolder, post, position, null);
        }

        @Override
        public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.post_item, parent, false);

            return new PostViewHolder(view);
        }
    };
}
 
Example #16
Source File: RxFirebaseHelper.java    From EasyFirebase with Apache License 2.0 6 votes vote down vote up
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) {

                }
            });
        }
    });
}
 
Example #17
Source File: KeepSyncedTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example #18
Source File: HomeView.java    From BloodBank with GNU General Public License v3.0 5 votes vote down vote up
private void AddPosts()
{
    Query allposts = donor_ref.child("posts");
    pd.show();
    allposts.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if(dataSnapshot.exists()) {

                for (DataSnapshot singlepost : dataSnapshot.getChildren()) {
                    CustomUserData customUserData = singlepost.getValue(CustomUserData.class);
                    postLists.add(customUserData);
                    restAdapter.notifyDataSetChanged();
                }
                pd.dismiss();
            }
            else
            {
                Toast.makeText(getActivity(), "Database is empty now!",
                        Toast.LENGTH_LONG).show();
            }
        }

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

            Log.d("User", databaseError.getMessage());

        }
    });

}
 
Example #19
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Observable<DataSnapshot> changes(@NonNull final Query query) {
    return Observable.create(new ObservableOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final ObservableEmitter<DataSnapshot> emit) throws Exception {
            final ValueEventListener listener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!emit.isDisposed()) {
                        emit.onNext(dataSnapshot);
                    }
                }

                @Override
                public void onCancelled(DatabaseError e) {
                    if (!emit.isDisposed()) {
                        emit.onError(e.toException());
                    }
                }
            };

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

            query.addValueEventListener(listener);
        }
    });
}
 
Example #20
Source File: KeepSyncedTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example #21
Source File: ReadFuture.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public ReadFuture(final Query ref) {
  this(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          return true;
        }
      });
}
 
Example #22
Source File: ReadFuture.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
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;
        }
      });
}
 
Example #23
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Observable<DataSnapshot> changes(@NonNull final Query query) {
    return Observable.create(new ObservableOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final ObservableEmitter<DataSnapshot> emit) throws Exception {
            final ValueEventListener listener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!emit.isDisposed()) {
                        emit.onNext(dataSnapshot);
                    }
                }

                @Override
                public void onCancelled(DatabaseError e) {
                    if (!emit.isDisposed()) {
                        emit.onError(e.toException());
                    }
                }
            };

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

            query.addValueEventListener(listener);
        }
    });
}
 
Example #24
Source File: ResolverQueryOrderByTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Test
public void resolve_orderByChild() {
    // Given
    OrderByClause orderByClause = new OrderByClause();
    orderByClause.setOrderByMode(OrderByMode.ORDER_BY_CHILD);
    orderByClause.setArgument("test_argument");
    Query query = PowerMockito.mock(Query.class);
    ResolverQueryOrderBy resolver = new ResolverQueryOrderBy();

    // When
    resolver.resolve(orderByClause, query);

    // Then
    Mockito.verify(query, VerificationModeFactory.times(1)).orderByChild(Mockito.eq("test_argument"));
}
 
Example #25
Source File: ResolverQueryOrderByTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void resolve_orderByChild_withoutArgument() {
    // Given
    OrderByClause orderByClause = new OrderByClause();
    orderByClause.setOrderByMode(OrderByMode.ORDER_BY_CHILD);
    Query query = PowerMockito.mock(Query.class);
    ResolverQueryOrderBy resolver = new ResolverQueryOrderBy();

    // When
    resolver.resolve(orderByClause, query);

    // Then
    Mockito.verify(query, VerificationModeFactory.times(1)).orderByChild(Mockito.eq("test_argument"));
}
 
Example #26
Source File: ReadFuture.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public ReadFuture(final Query ref) {
  this(
      ref,
      new CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          return true;
        }
      });
}
 
Example #27
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: ResolverQueryOrderByTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Test
public void resolve_orderByKey() {
    // Given
    OrderByClause orderByClause = new OrderByClause();
    orderByClause.setOrderByMode(OrderByMode.ORDER_BY_KEY);
    Query query = PowerMockito.mock(Query.class);
    ResolverQueryOrderBy resolver = new ResolverQueryOrderBy();

    // When
    resolver.resolve(orderByClause, query);

    // Then
    Mockito.verify(query, VerificationModeFactory.times(1)).orderByKey();
}
 
Example #29
Source File: ResolverQueryOrderByTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Test
public void resolve_orderByValue() {
    // Given
    OrderByClause orderByClause = new OrderByClause();
    orderByClause.setOrderByMode(OrderByMode.ORDER_BY_VALUE);
    Query query = PowerMockito.mock(Query.class);
    ResolverQueryOrderBy resolver = new ResolverQueryOrderBy();

    // When
    resolver.resolve(orderByClause, query);

    // Then
    Mockito.verify(query, VerificationModeFactory.times(1)).orderByValue();
}
 
Example #30
Source File: ReadFuture.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
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);
}