Java Code Examples for com.google.firebase.database.DatabaseError

The following examples show how to use com.google.firebase.database.DatabaseError. These examples are extracted from open source projects. 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 Project: Walk-In-Clinic-Android-App   Source File: SignIn.java    License: MIT License 6 votes vote down vote up
public void updateUsers(){
    databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            users.clear();  // might need to remove
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                DataBaseUser usr = postSnapshot.getValue(DataBaseUser.class);
                users.add(usr);
            }
        }

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

        }
    });
}
 
Example 2
Source Project: Walk-In-Clinic-Android-App   Source File: SignUp.java    License: 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 3
/**
 * Receives a call from editPresenter upon user's button click.
 * Updates user data in db.
 */
public void updateUserDb() {
    final String userUid = mUser.getUid();
    mDatabaseReference.child("users").child(userUid).
            addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //DATA ALREADY EXISTS
                    String oldMail = String.valueOf(dataSnapshot.child("email").getValue());
                    if(!oldMail.equals(mUser.getEmail())) {
                        resetUserAuthMail(mUser.getEmail());
                    }
                    mDatabaseReference.child("users").child(userUid).setValue(mUser);
                    mPresenterEdit.sendToastRequestToView(2);
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.d("warning", "oncancelled");
                }
            });
}
 
Example 4
Source Project: UberClone   Source File: CustomerSettingsActivity.java    License: MIT License 6 votes vote down vote up
private void getUserInfo(){
    mCustomerDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if(map.get("name")!=null){
                    mName = map.get("name").toString();
                    mNameField.setText(mName);
                }
                if(map.get("phone")!=null){
                    mPhone = map.get("phone").toString();
                    mPhoneField.setText(mPhone);
                }
                if(map.get("profileImageUrl")!=null){
                    mProfileImageUrl = map.get("profileImageUrl").toString();
                    Glide.with(getApplication()).load(mProfileImageUrl).into(mProfileImage);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example 5
Source Project: UberClone   Source File: CallDriver.java    License: MIT License 6 votes vote down vote up
private void loadDriverInfo(String driverID) {
    FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl)
            .child(driverID).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user=dataSnapshot.getValue(User.class);

            if(user.getAvatarUrl()!=null &&
                    !TextUtils.isEmpty(user.getAvatarUrl()))
                Picasso.get().load(user.getAvatarUrl()).into(imgAvatar);
            tvName.setText(user.getName());
            tvPhone.setText(user.getPhone());
            tvRate.setText(user.getRates());
        }

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

        }
    });
}
 
Example 6
Source Project: firebase-admin-java   Source File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
public static Pair<ApiFuture<Void>, DatabaseReference.CompletionListener> wrapOnComplete(
    DatabaseReference.CompletionListener optListener) {
  if (optListener == null) {
    final SettableApiFuture<Void> future = SettableApiFuture.create();
    DatabaseReference.CompletionListener listener =
        new DatabaseReference.CompletionListener() {
          @Override
          public void onComplete(DatabaseError error, DatabaseReference ref) {
            if (error != null) {
              future.setException(error.toException());
            } else {
              future.set(null);
            }
          }
        };
    return new Pair<ApiFuture<Void>, DatabaseReference.CompletionListener>(future, listener);
  } else {
    // If a listener is supplied we do not want to create a Task
    return new Pair<>(null, optListener);
  }
}
 
Example 7
Source Project: geofire-android   Source File: GeoFire.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Removes the location for a key from this GeoFire.
 *
 * @param key                The key to remove from this GeoFire
 * @param completionListener A completion listener that is called once the location is successfully removed
 *                           from the server or an error occurred
 */
public void removeLocation(final String key, final CompletionListener completionListener) {
    if (key == null) {
        throw new NullPointerException();
    }
    DatabaseReference keyRef = this.getDatabaseRefForKey(key);
    if (completionListener != null) {
        keyRef.setValue(null, new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
                completionListener.onComplete(key, databaseError);
            }
        });
    } else {
        keyRef.setValue(null);
    }
}
 
Example 8
Source Project: kute   Source File: LoadPersonRoutesAsyncTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected ArrayList<Route> doInBackground(String... params) {
    //Return the retrieved list of person's  routes from firebase
    String id=params[0];
    String route_ref="Routes/"+id;
    DatabaseReference routes_ref= FirebaseDatabase.getInstance().getReference(route_ref);
    routes_ref.keepSynced(true);
    routes_ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot routes:dataSnapshot.getChildren()){
                Route temp=routes.getValue(Route.class);
                Log.i(TAG,temp.getName());
                routes_list.add(temp);
            }
            messenger_to_activity.onTaskCompleted(routes_list);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return null;
}
 
Example 9
Source Project: social-app-android   Source File: PostInteractor.java    License: Apache License 2.0 6 votes vote down vote up
public ValueEventListener hasCurrentUserLike(String postId, String userId, final OnObjectExistListener<Like> onObjectExistListener) {
    DatabaseReference databaseReference = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.POST_LIKES_DB_KEY)
            .child(postId)
            .child(userId);
    ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            onObjectExistListener.onDataChanged(dataSnapshot.exists());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "hasCurrentUserLike(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });

    databaseHelper.addActiveListener(valueEventListener, databaseReference);
    return valueEventListener;
}
 
Example 10
Source Project: outlay   Source File: CategoryFirebaseSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Observable<List<Category>> getAll() {
    return Observable.create(subscriber -> {
        mDatabase.child("users").child(currentUser.getId()).child("categories").orderByChild("order")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        List<Category> categories = new ArrayList<>();
                        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                            CategoryDto categoryDto = postSnapshot.getValue(CategoryDto.class);
                            categories.add(adapter.toCategory(categoryDto));
                        }
                        subscriber.onNext(categories);
                        subscriber.onCompleted();
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        subscriber.onError(databaseError.toException());
                    }
                });
    });


}
 
Example 11
Source Project: outlay   Source File: CategoryFirebaseSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Observable<Category> remove(Category category) {
    final Observable<Category> deleteCategory = Observable.create(subscriber -> {
        DatabaseReference catReference = mDatabase.child("users").child(currentUser.getId())
                .child("categories").child(category.getId());
        catReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                subscriber.onNext(category);
                subscriber.onCompleted();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                subscriber.onError(databaseError.toException());
            }
        });
        catReference.removeValue();
    });

    return deleteCategory;
}
 
Example 12
Source Project: rxfirebase   Source File: RxValue.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param emit
 * @return
 */
@NonNull
@CheckReturnValue
public static ValueEventListener listener(@NonNull final SingleEmitter<DataSnapshot> emit) {
    return new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!emit.isDisposed()) {
                emit.onSuccess(dataSnapshot);
            }
        }

        @Override
        public void onCancelled(DatabaseError e) {
            if (!emit.isDisposed()) {
                emit.onError(e.toException());
            }
        }
    };
}
 
Example 13
Source Project: firebase-admin-java   Source File: DataTestIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateAfterSetLeafNodeWorks() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  final Semaphore semaphore = new Semaphore(0);
  final Map<String, Object> expected = new MapBuilder().put("a", 1L).put("b", 2L).build();

  ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      if (DeepEquals.deepEquals(snapshot.getValue(), expected)) {
        semaphore.release();
      }
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });
  ref.setValueAsync(42);
  ref.updateChildrenAsync(expected);

  TestHelpers.waitFor(semaphore);
}
 
Example 14
Source Project: firebase-admin-java   Source File: RepoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCallOnComplete() {
  final Repo repo = newRepo();
  final AtomicReference<DatabaseError> errorResult = new AtomicReference<>();
  final AtomicReference<DatabaseReference> refResult = new AtomicReference<>();
  DatabaseReference.CompletionListener listener = new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference ref) {
      errorResult.set(error);
      refResult.set(ref);
    }
  };
  repo.callOnComplete(listener, null, new Path("/foo"));
  assertNull(errorResult.get());
  assertEquals("foo", refResult.get().getKey());

  DatabaseError ex = DatabaseError.fromCode(DatabaseError.WRITE_CANCELED);
  repo.callOnComplete(listener, ex, new Path("/bar"));
  assertEquals(ex, errorResult.get());
  assertEquals("bar", refResult.get().getKey());
}
 
Example 15
Source Project: friendlypix-android   Source File: ProfileActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void showSignedInUI(FirebaseUser firebaseUser) {
    Log.d(TAG, "Showing signed in UI");
    mSignInUi.setVisibility(View.GONE);
    mProfileUi.setVisibility(View.VISIBLE);
    mProfileUsername.setVisibility(View.VISIBLE);
    mProfilePhoto.setVisibility(View.VISIBLE);
    if (firebaseUser.getDisplayName() != null) {
        mProfileUsername.setText(firebaseUser.getDisplayName());
    }

    if (firebaseUser.getPhotoUrl() != null) {
        GlideUtil.loadProfileIcon(firebaseUser.getPhotoUrl().toString(), mProfilePhoto);
    }
    Map<String, Object> updateValues = new HashMap<>();
    updateValues.put("displayName", firebaseUser.getDisplayName() != null ? firebaseUser.getDisplayName() : "Anonymous");
    updateValues.put("photoUrl", firebaseUser.getPhotoUrl() != null ? firebaseUser.getPhotoUrl().toString() : null);

    FirebaseUtil.getPeopleRef().child(firebaseUser.getUid()).updateChildren(
            updateValues,
            new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError firebaseError, DatabaseReference databaseReference) {
                    if (firebaseError != null) {
                        Toast.makeText(ProfileActivity.this,
                                "Couldn't save user data: " + firebaseError.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
}
 
Example 16
Source Project: social-app-android   Source File: PostInteractor.java    License: Apache License 2.0 6 votes vote down vote up
public void getSinglePost(final String id, final OnPostChangedListener listener) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY).child(id);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null && dataSnapshot.exists()) {
                if (isPostValid((Map<String, Object>) dataSnapshot.getValue())) {
                    Post post = dataSnapshot.getValue(Post.class);
                    post.setId(id);
                    listener.onObjectChanged(post);
                } else {
                    listener.onError(String.format(context.getString(R.string.error_general_post), id));
                }
            } else {
                listener.onError(context.getString(R.string.message_post_was_removed));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getSinglePost(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 17
Source Project: buddysearch   Source File: FirebaseEntityStore.java    License: Apache License 2.0 6 votes vote down vote up
protected <T extends Entity, R> Observable<R> createIfNotExists(DatabaseReference databaseReference, T value, R successResponse) {
    return Observable.create(new Observable.OnSubscribe<R>() {
        @Override
        public void call(Subscriber<? super R> subscriber) {
            databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.getValue() == null) {
                        postQuery(databaseReference, value, false, successResponse)
                                .subscribe(subscriber);
                    } else {
                        subscriber.onNext(successResponse);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    subscriber.onError(new FirebaseException(databaseError.getMessage()));
                }
            });
        }
    });
}
 
Example 18
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 19
Source Project: firebase-admin-java   Source File: Repo.java    License: Apache License 2.0 6 votes vote down vote up
public void onDisconnectUpdate(
    final Path path,
    final Map<Path, Node> newChildren,
    final DatabaseReference.CompletionListener listener,
    Map<String, Object> unParsedUpdates) {
  connection.onDisconnectMerge(
      path.asList(),
      unParsedUpdates,
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("onDisconnect().updateChildren", path, error);
          if (error == null) {
            for (Map.Entry<Path, Node> entry : newChildren.entrySet()) {
              onDisconnect.remember(path.child(entry.getKey()), entry.getValue());
            }
          }
          callOnComplete(listener, error, path);
        }
      });
}
 
Example 20
Source Project: FaceT   Source File: MakeupProductFragment.java    License: 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 21
Source Project: firebase-admin-java   Source File: Repo.java    License: Apache License 2.0 6 votes vote down vote up
void callOnComplete(
    final DatabaseReference.CompletionListener onComplete,
    final DatabaseError error,
    final Path path) {
  if (onComplete != null) {
    final DatabaseReference ref;
    ChildKey last = path.getBack();
    if (last != null && last.isPriorityChildName()) {
      ref = InternalHelpers.createReference(this, path.getParent());
    } else {
      ref = InternalHelpers.createReference(this, path);
    }
    postEvent(
        new Runnable() {
          @Override
          public void run() {
            onComplete.onComplete(error, ref);
          }
        });
  }
}
 
Example 22
Source Project: firebase-android-sdk   Source File: Repo.java    License: Apache License 2.0 6 votes vote down vote up
private void runOnDisconnectEvents() {
  Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock);
  final List<Event> events = new ArrayList<Event>();

  onDisconnect.forEachTree(
      Path.getEmptyPath(),
      new SparseSnapshotTree.SparseSnapshotTreeVisitor() {
        @Override
        public void visitTree(Path prefixPath, Node node) {
          Node existing = serverSyncTree.calcCompleteEventCache(prefixPath, new ArrayList<>());
          Node resolvedNode =
              ServerValues.resolveDeferredValueSnapshot(node, existing, serverValues);
          events.addAll(serverSyncTree.applyServerOverwrite(prefixPath, resolvedNode));
          Path affectedPath = abortTransactions(prefixPath, DatabaseError.OVERRIDDEN_BY_SET);
          rerunTransactions(affectedPath);
        }
      });
  onDisconnect = new SparseSnapshotTree();
  this.postEvents(events);
}
 
Example 23
Source Project: social-app-android   Source File: ProfileInteractor.java    License: Apache License 2.0 6 votes vote down vote up
public void getProfileSingleValue(String id, final OnObjectChangedListener<Profile> listener) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.PROFILES_DB_KEY).child(id);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Profile profile = dataSnapshot.getValue(Profile.class);
            listener.onObjectChanged(profile);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            listener.onError(databaseError.getMessage());
            LogUtil.logError(TAG, "getProfileSingleValue(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 24
/**
 * Get logged user data from DB, called from the profilePresenter which is called
 * from the ProfileFragment onViewCreated.
 * Returns user data to the presenter.
 */
public void getUserDataFromDb() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    final String uid = user.getUid();
    mDatabaseReference.child("users").child(uid).addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    mUser.setName(String.valueOf(dataSnapshot.child("name").getValue()));
                    mUser.setPhone(String.valueOf(dataSnapshot.child("phone").getValue()));
                    mUser.setEmail(String.valueOf(dataSnapshot.child("email").getValue()));
                    mUser.setUid(uid);
                    mUser.setRole(String.valueOf(dataSnapshot.child("role").getValue()));
                    checkAndSetCurrentUserToken(uid);
                    mPresenterEdit.onReceivedUserDataFromDb(mUser);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            }
    );
}
 
Example 25
/**
 * 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 26
Source Project: social-app-android   Source File: PostInteractor.java    License: Apache License 2.0 6 votes vote down vote up
public ValueEventListener hasCurrentUserLike(String postId, String userId, final OnObjectExistListener<Like> onObjectExistListener) {
    DatabaseReference databaseReference = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.POST_LIKES_DB_KEY)
            .child(postId)
            .child(userId);
    ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            onObjectExistListener.onDataChanged(dataSnapshot.exists());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "hasCurrentUserLike(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });

    databaseHelper.addActiveListener(valueEventListener, databaseReference);
    return valueEventListener;
}
 
Example 27
Source Project: social-app-android   Source File: FollowInteractor.java    License: Apache License 2.0 6 votes vote down vote up
public void getFollowingsList(String targetUserId, OnDataChangedListener<String> onDataChangedListener) {
    getFollowingsRef(targetUserId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> list = new ArrayList<>();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Following following = snapshot.getValue(Following.class);

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

            }
            onDataChangedListener.onListChanged(list);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logDebug(TAG, "getFollowingsList, onCancelled");
        }
    });
}
 
Example 28
Source Project: UberClone   Source File: DriverTracking.java    License: MIT License 6 votes vote down vote up
private void displayLocation(){
    //add driver location
    if(driverMarker!=null)driverMarker.remove();
    driverMarker=mMap.addMarker(new MarkerOptions().position(new LatLng(Common.currentLat, Common.currentLng))
    .title("You").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marker)));
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Common.currentLat, Common.currentLng), 14f));
    geoFire.setLocation(Common.userID,
            new GeoLocation(Common.currentLat, Common.currentLng),
            new GeoFire.CompletionListener() {
                @Override
                public void onComplete(String key, DatabaseError error) {

                }
            });
    //remove route
    if(direction!=null)direction.remove();
      getDirection();

}
 
Example 29
private static void doRead(
    DatabaseReference ref, final boolean shouldSucceed, final boolean shouldTimeout)
    throws InterruptedException {
  final CountDownLatch lock = new CountDownLatch(1);
  final AtomicBoolean success = new AtomicBoolean(false);
  ref.addListenerForSingleValueEvent(
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          success.compareAndSet(false, true);
          lock.countDown();
        }

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

  boolean finished = lock.await(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  if (shouldTimeout) {
    assertTrue("Read finished (expected to timeout).", !finished);
  } else if (shouldSucceed) {
    assertTrue("Read timed out (expected to succeed).", finished);
    assertTrue("Read failed (expected to succeed).", success.get());
  } else {
    assertTrue("Read timed out (expected to fail).", finished);
    assertTrue("Read successful (expected to fail).", !success.get());
  }
}
 
Example 30
Source Project: firebase-admin-java   Source File: ReadFuture.java    License: Apache License 2.0 5 votes vote down vote up
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);
}