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

项目:AndroidBackendlessChat    文件:BChatcatNetworkAdapter.java   
@Override
public Promise<Void, BError, Void> changePassword(String email, String oldPassword, String newPassword){

    final Deferred<Void, BError, Void> deferred = new DeferredObject<>();

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

    OnCompleteListener<Void> resultHandler = new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                deferred.resolve(null);
            } else {
                deferred.reject(getFirebaseError(DatabaseError.fromException(task.getException())));

            }
        }
    };

    user.updatePassword(newPassword).addOnCompleteListener(resultHandler);

    return deferred.promise();
}
项目:CowBit    文件:FirebaseHelper.java   
public void readClientID() {

        String path = String.format("/users/%s/clientID", mCurrentUser.getUid());

        DatabaseReference clientIDRef;
        clientIDRef = mDatabase.getReference(path);

        ValueEventListener clientIDRefListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
//                clientIDRef.removeEventListener(clientIDRefListener);
                mClientID = dataSnapshot.getValue(String.class);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                mClientID = null;
//                clientIDRef.removeEventListener(clientIDRefListener);
            }
        };
        clientIDRef.addListenerForSingleValueEvent(clientIDRefListener);
    }
项目:firebase-admin-java    文件:Utilities.java   
public static Pair<Task<Void>, DatabaseReference.CompletionListener> wrapOnComplete(
    DatabaseReference.CompletionListener optListener) {
  if (optListener == null) {
    final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
    DatabaseReference.CompletionListener listener =
        new DatabaseReference.CompletionListener() {
          @Override
          public void onComplete(DatabaseError error, DatabaseReference ref) {
            if (error != null) {
              source.setException(error.toException());
            } else {
              source.setResult(null);
            }
          }
        };
    return new Pair<>(source.getTask(), listener);
  } else {
    // If a listener is supplied we do not want to create a Task
    return new Pair<>(null, optListener);
  }
}
项目:IM_Here    文件:UserDataFirebaseSearch.java   
public void setUserRelation(final String USER_EMAIL,
                            final ViewAppHolder.SearchViewHolder searchViewHolder){

    FirebaseHelper.getUserDatabaseReference(USER_LINK_FIREBASE)
            .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean userInFriendList = checkUserInFriendList(dataSnapshot,USER_EMAIL);
            boolean userInFriendRequest = checkUserInFriendRequest(dataSnapshot,USER_EMAIL);
            boolean currentUserSendFriendRequest = checkCurrentUserRequestSend(dataSnapshot,USER_EMAIL);

            userSearchUi.setUserView(userInFriendList, userInFriendRequest,
                    currentUserSendFriendRequest, searchViewHolder,
                    USER_EMAIL);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
项目:EasyFirebase    文件:EasyFirebaseDb.java   
public Observable<Void> push() {
    final DatabaseReference child = easyFirebaseDb.databaseReference.child(name);
    for (Map.Entry<String, Object> entry : values.entrySet()) {
        child.child(entry.getKey()).setValue(entry.getValue());
    }
    return Observable.create(new Observable.OnSubscribe<Void>() {
                                 @Override
                                 public void call(final Subscriber<? super Void> subscriber) {
                                     child.addListenerForSingleValueEvent(new ValueEventListener() {
                                         @Override
                                         public void onDataChange(DataSnapshot dataSnapshot) {
                                             subscriber.onNext(null);
                                             subscriber.onCompleted();
                                         }

                                         @Override
                                         public void onCancelled(DatabaseError databaseError) {
                                             subscriber.onError(databaseError.toException());
                                         }
                                     });
                                 }
                             });
}
项目:firebase-admin-java    文件:SyncTree.java   
@Override
public List<? extends Event> onListenComplete(DatabaseError error) {
  if (error == null) {
    QuerySpec query = this.view.getQuery();
    if (tag != null) {
      return SyncTree.this.applyTaggedListenComplete(tag);
    } else {
      return SyncTree.this.applyListenComplete(query.getPath());
    }
  } else {
    logger.warn("Listen at " + view.getQuery().getPath() + " failed: " + error.toString());

    // If a listen failed, kill all of the listeners here, not just the one that triggered the
    // error. Note that this may need to be scoped to just this listener if we change
    // permissions on filtered children
    return SyncTree.this.removeAllEventRegistrations(view.getQuery(), error);
  }
}
项目: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) {

        }
    });
}
项目:Runnest    文件:FirebaseHelperTest.java   
@Test
public void canGetProfilePicUrl() {
    final String testUserForPic = "Test User for Pic";
    final String url = "http://url.test.ch";
    firebaseHelper.addOrUpdateUser(TEST_USER, testUserForPic);
    firebaseHelper.setOrUpdateProfilePicUrl(testUserForPic, url);
    firebaseHelper.getProfilePicUrl(testUserForPic, new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String fetchedUrl = (String) dataSnapshot.getValue();
            Assert.assertTrue(url.equals(fetchedUrl));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
}
项目:Botanist    文件:AccountController.java   
@Override
public void load() {
    showProgressDialog(getActivity().getString(R.string.loading_text));
    getDatabaseManager().getUserReference().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                mUser = dataSnapshot.getValue(User.class);
                populateUserInfo();
                populateUserStatsChart();
                loadBadge();
            }
            hideProgressDialog();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            hideProgressDialog();
        }
    });
}
项目:SmartHome    文件:DoorSettings.java   
public DoorSettings(){
    database = FirebaseDatabase.getInstance();
    doorSettingsRef = database.getReference("doorsettings");

    doorSettingsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.e("db", "dbok in doorsettings.java");
            active = ((boolean) dataSnapshot.child("active").getValue());
            lockH = ((Number) dataSnapshot.child("lockH").getValue()).intValue();
            lockM = ((Number) dataSnapshot.child("lockM").getValue()).intValue();
            unlockH = ((Number) dataSnapshot.child("unlockH").getValue()).intValue();
            unlockM = ((Number) dataSnapshot.child("unlockM").getValue()).intValue();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("db", "dberror in doorsettings.java");
            Log.e("db",databaseError.toString());
            active = false;
        }
    });
}
项目:showcase-android    文件:RxFirebaseDatabase.java   
/**
 * Update the specific child keys to the specified values.
 *
 * @param ref        reference represents a particular location in your database.
 * @param updateData The paths to update and their new values
 * @return a {@link Completable} which is complete when the update children call finish successfully.
 */
@NonNull
public static Completable updateChildren(@NonNull final DatabaseReference ref,
                                         @NonNull final Map<String, Object> updateData) {
   return Completable.create(new CompletableOnSubscribe() {
      @Override
      public void subscribe(final CompletableEmitter emitter) throws Exception {
         ref.updateChildren(updateData, new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError error, DatabaseReference databaseReference) {
               if (error != null) {
                  emitter.onError(new RxFirebaseDataException(error));
               } else {
                  emitter.onComplete();
               }
            }
         });
      }
   });
}
项目:Quadro    文件:AboutFragment.java   
@Override
public void onStart() {
    super.onStart();
    final ValueEventListener userListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Details detailsModel = dataSnapshot.getValue(Details.class);

            if (dataSnapshot.exists()) {
                aboutMeTextView.setText(detailsModel.aboutMe);
                birthDateTextView.setText(detailsModel.birthDate);
                heightTextView.setText(detailsModel.height);
            } else {

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
    mDatabase.addValueEventListener(userListener);
}
项目:androidadvanced    文件:FirebaseAPI.java   
public void checkForData(final FirebaseActionListenerCallback listener){
    ValueEventListener postListener = new ValueEventListener() {
        @Override public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
            if (dataSnapshot.getChildrenCount() > 0) {
                listener.onSuccess();
            } else {
                listener.onError(null);
            }
        }

        @Override public void onCancelled(DatabaseError databaseError) {
            Log.d("FIREBASE API", databaseError.getMessage());
        }
    };
    mPhotoDatabaseReference.addValueEventListener(postListener);
}
项目:chat-sdk-android-push-firebase    文件:BChatcatNetworkAdapter.java   
@Override
public Promise<Void, BError, Void> changePassword(String email, String oldPassword, String newPassword){

    final Deferred<Void, BError, Void> deferred = new DeferredObject<>();

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

    OnCompleteListener<Void> resultHandler = new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                deferred.resolve(null);
            } else {
                deferred.reject(getFirebaseError(DatabaseError.fromException(task.getException())));

            }
        }
    };

    user.updatePassword(newPassword).addOnCompleteListener(resultHandler);

    return deferred.promise();
}
项目:cat-is-a-dog    文件:FollowRequestRepository.java   
/**
 * Get a FollowRequest from Firebase.
 * @param key
 * @param resultListener
 */
@Override
public void get(String key, final OnResultListener<FollowRequest> resultListener) {
    mFollowRequestRef.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            FollowRequest request = dataSnapshot.getValue(FollowRequest.class);
            resultListener.onResult(request);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
项目:firebase-admin-java    文件:RulesTestIT.java   
@Test
public void testAuthenticatedImmediatelyAfterTokenChange() throws Exception {
  DatabaseConfig config = TestHelpers.getDatabaseConfig(masterApp);
  AuthTokenProvider originalProvider = config.getAuthTokenProvider();
  try {
    TestTokenProvider provider = new TestTokenProvider(TestHelpers.getExecutorService(config));
    config.setAuthTokenProvider(provider);

    DatabaseReference root = FirebaseDatabase.getInstance(masterApp).getReference();
    DatabaseReference ref = root.child(writer.getPath().toString());

    String token = TestOnlyImplFirebaseTrampolines.getToken(masterApp, true);
    provider.setToken(token);

    DatabaseError err = new WriteFuture(ref.child("any_auth"), true).timedGet();
    assertNull(err);
  } finally {
    config.setAuthTokenProvider(originalProvider);
  }
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testSetPriority() throws InterruptedException {
  final DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ref.setValueAsync("hello!");
  final Semaphore semaphore = new Semaphore(0);
  ref.setPriority(10, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference callbackRef) {
      assertEquals(ref, callbackRef);
      assertNull(error);
      semaphore.release(1);
    }
  });

  assertTrue(semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
项目:vc    文件:AddressService.java   
public static List<Address> getAllAddresses(){

    final List<Address> Addresses=new ArrayList<Address>();    

// Attach a listener to read the data at our posts reference
AddressRef.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Address post = dataSnapshot.getValue(Address.class);
        Addresses.add(post);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});

return Addresses;
    }
项目:IM_Here    文件:UserDataFirebaseGeofence.java   
private void setListenerToUserLocation(){
    FirebaseHelper.getUserLocation(USER_LINK_FIREBASE)
            .addValueEventListener(userLocationGeofenceListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    CurrentLocation currentUserLocation =
                            dataSnapshot.getValue(CurrentLocation.class);
                    // get user location.
                    final Location userLocation = new Location(Constants.CURRENT_USER_LOCATION_PROVIDER);
                    if(currentUserLocation != null) {

                        userLocation.setLongitude(currentUserLocation.getLocationLongitude());
                        userLocation.setLatitude(currentUserLocation.getLocationLatitude());
                        Log.e("location called","changed");
                        checkLocationWithRespectToFlags(userLocation);
                        checkLocationWithRespectToDetections(userLocation);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}
项目:IM_Here    文件:UserDataFirebaseMainActivity.java   
public static void newNotificationsNumberIncrement(){
    FirebaseHelper.getUserNewNotificationsNumber(USER_LINK_FIREBASE)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    Integer newNotifications = dataSnapshot.getValue(int.class);
                    Log.e("notification number ",String.valueOf(newNotifications));
                    if(newNotifications != null) {
                        newNotifications++;
                        FirebaseHelper.getUserNewNotificationsNumber(USER_LINK_FIREBASE)
                                .setValue(newNotifications);
                    }else{
                        FirebaseHelper.getUserNewNotificationsNumber(USER_LINK_FIREBASE)
                                .setValue(1);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}
项目:firebase-admin-java    文件:UtilitiesTest.java   
@Test
public void testWrapOnCompleteErrorResult() {
  Pair<Task<Void>, DatabaseReference.CompletionListener> result =
      Utilities.wrapOnComplete(null);
  assertNotNull(result.getFirst());
  assertNotNull(result.getSecond());
  try {
    result.getFirst().getResult();
    fail("No error thrown for pending task");
  } catch (Exception e) {
    // expected
  }

  result.getSecond().onComplete(DatabaseError.fromStatus("test error"), null);
  assertNotNull(result.getFirst().getException());
}
项目:RxFirebase2    文件:RunTransactionOnSubscribe.java   
@Override public void subscribe(final CompletableEmitter emitter) {
  final Transaction.Handler handler = new Transaction.Handler() {
    @Override public Transaction.Result doTransaction(MutableData mutableData) {
      try {
        return task.apply(mutableData);
      } catch (Exception e) {
        //TODO: Is this enough?
        throw new RuntimeException(e);
      }
    }

    @Override public void onComplete(DatabaseError databaseError, boolean committed,
        DataSnapshot dataSnapshot) {
      if (!emitter.isDisposed()) {
        if (null == databaseError) {
          emitter.onComplete();
        } else {
          emitter.onError(databaseError.toException());
        }
      }
    }
  };

  ref.runTransaction(handler, fireLocalEvents);
}
项目:Viajes    文件:HotelsRepository.java   
@Override
public void getHotels(@Nullable final LoadHotelCallback callback) {
    list.clear();
    categoryRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!dataSnapshot.exists()){
                callback.onDataNotAvailable();
            }
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                final Hotel item = ds.getValue(Hotel.class);
                item.setItemId(ds.getKey());
                list.add(item);
            }
            callback.onHotelsLoaded(list);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            callback.onDataNotAvailable();

        }
    });
}
项目: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));
            }
         });
      }
   });
}
项目:couch-potatoes    文件:PreferenceChart.java   
private void displaySubcategories() {
    dbHelper.getDb().getReference( dbHelper.getInterestSubcategoryPath() ).child( interest ).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           for ( DataSnapshot subcategory : dataSnapshot.getChildren() ) {
               String currSubcategory = (String) subcategory.getValue();
               subcategoryList.add( currSubcategory );
           }

           subcategoryAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
项目:chat-sdk-android-push-firebase    文件:BChatcatNetworkAdapter.java   
@Override
public Promise<Void, BError, Void> sendPasswordResetMail(String email){

    final Deferred<Void, BError, Void> deferred = new DeferredObject<>();

    OnCompleteListener<Void> resultHandler = new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                if(DEBUG) Timber.v("Email sent");
                deferred.resolve(null);
            } else {
                deferred.reject(getFirebaseError(DatabaseError.fromException(task.getException())));

            }
        }
    };

    FirebaseAuth.getInstance().sendPasswordResetEmail(email).addOnCompleteListener(resultHandler);

    return deferred.promise();
}
项目:social-app-android    文件:DatabaseHelper.java   
public void decrementCommentsCount(String postId, final OnTaskCompleteListener onTaskCompleteListener) {
    DatabaseReference postRef = database.getReference("posts/" + postId + "/commentsCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= 1) {
                mutableData.setValue(currentValue - 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating comments count transaction is completed.");
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(true);
            }
        }
    });
}
项目:Forager    文件:StartGame.java   
private void subtractFromDistanceRemaining(final DatabaseReference databaseReference, FirebaseUser firebaseUser) {
    databaseReference.child("global")
            .child("distanceRemaining")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Update the database
                    subtractFromDistanceRemaining(databaseReference, (dataSnapshot.getValue(Long.class).intValue() - 1));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, "Database Error Occurred", databaseError.toException());
                    FirebaseCrash.report(databaseError.toException());
                }
            });
}
项目:MavsSnapUp    文件:AddItemActivity.java   
protected void populateInterestList() {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, myListName);

    mInterestedList.setAdapter(adapter);

    mInterestedList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            mUser.child(myListID.get(i)).child("phone").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", String.valueOf(dataSnapshot.getValue()), null)));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });
}
项目:androidadvanced    文件:FirebaseHelper.java   
public void notifyContactsOfConnectionChange(final boolean online, final boolean signoff) {
    final String myEmail = getAuthUserEmail();
    getMyContactsReference().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot child : snapshot.getChildren()) {
                String email = child.getKey();
                DatabaseReference reference = getOneContactReference(email, myEmail);
                reference.setValue(online);
            }
            if (signoff){
                FirebaseAuth.getInstance().signOut();
            }
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
        }
    });
}
项目:MavsSnapUp    文件:AdminActivity.java   
private void loaditems() {
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            items.clear();
            for(DataSnapshot snap : dataSnapshot.getChildren()) {
                items.add(snap.getValue(String.class));
            }
            loadListView();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
项目:AndroidBackendlessChat    文件:BUserWrapper.java   
public Promise<BUser, BError, Void> push(){
    if (DEBUG) Timber.v("push");

    final Deferred<BUser, BError, Void> deferred = new DeferredObject<>();

    ref().updateChildren(serialize(), new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
            if (firebaseError == null)
            {
                deferred.resolve(model);
            }
            else deferred.reject(getFirebaseError(firebaseError));
        }
    });

    // index should be updated whenever the user is pushed
    updateIndex();

    return deferred.promise();
}
项目:Make-A-Pede-Android-App    文件:HomeActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    setContentView(R.layout.activity_home);

    setTitle("");

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference buttonsRef = database.getReference("/buttons");

    buttonsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int childrenCount = (int) dataSnapshot.getChildrenCount();

            Random random = new Random(System.currentTimeMillis());
            int index = random.nextInt(childrenCount);

            FbLinkAction action = dataSnapshot.child(String.valueOf(index)).getValue(FbLinkAction.class);
            fbLinkText = action.text;
            fbLinkUrl = action.link;
            fbLinkActionText = action.action;

            Snackbar snackbar = Snackbar.make(
                    findViewById(R.id.coordinator_layout),
                    fbLinkText,
                    Snackbar.LENGTH_INDEFINITE);

            snackbar.setAction(fbLinkActionText, HomeActivity.this::onFbLinkActionClicked);

            snackbar.show();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}
项目:couch-potatoes    文件:MatchingActivity.java   
public void fetchPotentDatesFromFirebase () {
    dbHelper.getDb().getReference( dbHelper.getPotentDatePath() + dbHelper.getAuth().getUid() ).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterator<DataSnapshot> potentDates = dataSnapshot.getChildren().iterator();

            matchedDateList.clear();

            while ( potentDates.hasNext() ) {
                matchedDateList.add( (String) potentDates.next().getValue() );
            }

            adapter.notifyDataSetChanged();
            viewPager.setAdapter(adapter);
            viewPager.setCurrentItem( currTab );

            // NOTE: Temporary workaround for now: ( Want functionality before Layout tabs are pressed )
            // Try to fetch profile pic from Firebase and update ImageView
            // If profile pic is null, display default profile pic instead
            if ( !matchedDateList.isEmpty() ) {
                displayPotentMatchProfilePic( matchedDateList.get(0) );
                addLikeDislikeListeners();
            }

            // Done fetching potent matches from Firebase
            // Hide spinner and display Matching Activity Views
            hideProgressBar();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}
项目:Show_Chat    文件:MovieFragment.java   
private void getListGroup(){
    Utilities.getFirebaseDBReference().child("user/"+ StaticConfig.UID+"/subscribed/movies").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            try {
                if (dataSnapshot.getValue() != null) {
                    HashMap mapListGroup = (HashMap) dataSnapshot.getValue();
                    Iterator iterator = mapListGroup.keySet().iterator();
                    while (iterator.hasNext()) {
                        String idGroup = mapListGroup.get(iterator.next().toString()).toString();
                        Group newGroup = new Group();
                        newGroup.id = idGroup;
                        listGroup.add(newGroup);
                    }
                    getGroupInfo(0);
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                    adapter.notifyDataSetChanged();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    });
}
项目:firebase-admin-java    文件:Repo.java   
private static DatabaseError fromErrorCode(String optErrorCode, String optErrorReason) {
  if (optErrorCode != null) {
    return DatabaseError.fromStatus(optErrorCode, optErrorReason);
  } else {
    return null;
  }
}
项目:social-app-android    文件:DatabaseHelper.java   
public ValueEventListener getPost(final String id, final OnPostChangedListener listener) {
    DatabaseReference databaseReference = getDatabaseReference().child("posts").child(id);
    ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                if (isPostValid((Map<String, Object>) dataSnapshot.getValue())) {
                    Post post = dataSnapshot.getValue(Post.class);
                    if (post != null) {
                        post.setId(id);
                    }
                    listener.onObjectChanged(post);
                } else {
                    listener.onError(String.format(context.getString(R.string.error_general_post), id));
                }
            } else {
                listener.onObjectChanged(null);
            }
        }

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

    activeListeners.put(valueEventListener, databaseReference);
    return valueEventListener;
}
项目:firebase-admin-java    文件:Repo.java   
private void ackWriteAndRerunTransactions(long writeId, Path path, DatabaseError error) {
  if (error != null && error.getCode() == DatabaseError.WRITE_CANCELED) {
    // This write was already removed, we just need to ignore it...
  } else {
    boolean success = error == null;
    List<? extends Event> clearEvents =
        serverSyncTree.ackUserWrite(writeId, !success, /*persist=*/ true, serverClock);
    if (clearEvents.size() > 0) {
      rerunTransactions(path);
    }
    postEvents(clearEvents);
  }
}
项目:firebase-admin-java    文件:Repo.java   
public void setValue(
    final Path path,
    Node newValueUnresolved,
    final DatabaseReference.CompletionListener onComplete) {
  if (operationLogger.logsDebug()) {
    operationLogger.debug("set: " + path);
  }
  if (dataLogger.logsDebug()) {
    dataLogger.debug("set: " + path + " " + newValueUnresolved);
  }

  Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock);
  Node newValue = ServerValues.resolveDeferredValueSnapshot(newValueUnresolved, serverValues);

  final long writeId = this.getNextWriteId();
  List<? extends Event> events =
      this.serverSyncTree.applyUserOverwrite(
          path, newValueUnresolved, newValue, writeId, /*visible=*/ true, /*persist=*/ true);
  this.postEvents(events);

  connection.put(
      path.asList(),
      newValueUnresolved.getValue(true),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("setValue", path, error);
          ackWriteAndRerunTransactions(writeId, path, error);
          callOnComplete(onComplete, error, path);
        }
      });

  Path affectedPath = abortTransactions(path, DatabaseError.OVERRIDDEN_BY_SET);
  this.rerunTransactions(affectedPath);
}
项目:firebase-admin-java    文件:Repo.java   
public void purgeOutstandingWrites() {
  if (operationLogger.logsDebug()) {
    operationLogger.debug("Purging writes");
  }
  List<? extends Event> events = serverSyncTree.removeAllWrites();
  postEvents(events);
  // Abort any transactions
  abortTransactions(Path.getEmptyPath(), DatabaseError.WRITE_CANCELED);
  // Remove outstanding writes from connection
  connection.purgeOutstandingWrites();
}