當前位置: 首頁>>代碼示例>>Java>>正文


Java DatabaseReference類代碼示例

本文整理匯總了Java中com.google.firebase.database.DatabaseReference的典型用法代碼示例。如果您正苦於以下問題:Java DatabaseReference類的具體用法?Java DatabaseReference怎麽用?Java DatabaseReference使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DatabaseReference類屬於com.google.firebase.database包,在下文中一共展示了DatabaseReference類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: deleteGroupFromUser

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
private static void deleteGroupFromUser(final String groupId, String userId) {
    final DatabaseReference currentUserGroupsRef = userDataRef.child(userId).child("groups");
    currentUserGroupsRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                if (ds.getValue().equals(groupId)) {
                    currentUserGroupsRef.child(ds.getKey()).removeValue();
                    pullFromFirebase(2); // Fetch group data from Firebase from new list
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
 
開發者ID:a-deda,項目名稱:share-location,代碼行數:20,代碼來源:FirebaseHelper.java

示例2: onBindViewHolder

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
@Override
public void onBindViewHolder(SwitchesAdapter.SwitchViewHolder holder, int position) {
    final Switch switch1 = mSwitches.get(position);

    holder.mSwitchTextView.setText(switch1.getName().toUpperCase().replace("PIN", "").replace("LIGHTBULB", "LIGHT BULB"));

    holder.mSwitchToggel.setBackgroundDrawable(switch1.getIcon());
    holder.mSwitchToggel.setOnCheckedChangeListener(null);
    holder.mSwitchToggel.setChecked(switch1.getStatus());
    holder.mSwitchToggel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch1.setStatus(isChecked);

            DatabaseReference switchRef = mDatabaseReference.child(switch1.getName()).getRef();
            switchRef.setValue(switch1);

            notifyDataSetChanged();
        }
    });
}
 
開發者ID:kevalpatel2106,項目名稱:smartswitch,代碼行數:22,代碼來源:SwitchesAdapter.java

示例3: updateChildren

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
public <T> void updateChildren(DatabaseReference databaseReference,
        @NonNull final ObservableEmitter<T> emitter, Map<String, Object> childUpdates) {
    if (isNetworkAvailable) {
        databaseReference.updateChildren(childUpdates, (databaseError, databaseReference1) -> {
            if (emitter.isDisposed()) {
                return;
            }
            if (databaseError == null) {
                emitter.onComplete();
            } else {
                emitter.onError(new Throwable(databaseError.getMessage()));
            }
        });
    } else {
        databaseReference.updateChildren(childUpdates);
        emitter.onComplete();
    }
}
 
開發者ID:riteshakya037,項目名稱:Subs,代碼行數:19,代碼來源:DatabaseCompletionListener.java

示例4: testAuthenticatedImmediatelyAfterTokenChange

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
@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);
  }
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:21,代碼來源:RulesTestIT.java

示例5: searchPostsByAuthor

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
protected List<Post> searchPostsByAuthor(Author author) {
    DatabaseReference myRef = mFirebaseInstance.getReference("post");
    myRef.orderByChild("author/key").equalTo(author.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<Post> result = new ArrayList<>();
            for (DataSnapshot child : dataSnapshot.getChildren()) {
                Post post = child.getValue(Post.class);
                result.add(post);
            }
            searchPostsByAuthorCount++;
            if(searchPostsByAuthorCount== ITERATIONS){
                logEvent("Search Posts by Authors ("+ ITERATIONS +")", initialTimeSearchPostsByAuthor, new Date());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
    return null;
}
 
開發者ID:AmeliaPessoa,項目名稱:DBPA,代碼行數:22,代碼來源:Firebase.java

示例6: onCreateView

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_journal_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        FirebaseDatabase dbRef = FirebaseDatabase.getInstance();
        FirebaseAuth auth = FirebaseAuth.getInstance();
        FirebaseUser user = auth.getCurrentUser();
        DatabaseReference userRef = dbRef.getReference(user.getUid());
        userRef.addChildEventListener (chEvListener);
        userRef.addValueEventListener(valEvListener);
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        adapter = new JournalAdapter(allTrips, mListener);
        recyclerView.setAdapter(adapter);
    }
    return view;
}
 
開發者ID:gvsucis,項目名稱:mobile-app-dev-book,代碼行數:26,代碼來源:JournalFragment.java

示例7: testWriteLeafNodeExpectValue

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
@Test
public void testWriteLeafNodeExpectValue() throws InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  final EventHelper readerHelper = new EventHelper().addValueExpectation(reader, 42)
      .startListening(true);
  final EventHelper writerHelper = new EventHelper().addValueExpectation(writer, 42)
      .startListening(true);

  ZombieVerifier.verifyRepoZombies(refs);

  writer.setValueAsync(42);
  assertTrue(writerHelper.waitForEvents());
  assertTrue(readerHelper.waitForEvents());
  writerHelper.cleanup();
  readerHelper.cleanup();
  ZombieVerifier.verifyRepoZombies(refs);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:21,代碼來源:EventTestIT.java

示例8: testWriteNestedLeafNodeWaitForEvents

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
@Test
public void testWriteNestedLeafNodeWaitForEvents() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;
  EventHelper helper =
      new EventHelper()
          .addChildExpectation(ref, Event.EventType.CHILD_ADDED, "foo")
          .addValueExpectation(ref)
          .startListening(true);

  ZombieVerifier.verifyRepoZombies(ref);

  ref.child("foo").setValueAsync(42);
  assertTrue(helper.waitForEvents());
  ZombieVerifier.verifyRepoZombies(ref);
  helper.cleanup();
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:17,代碼來源:EventTestIT.java

示例9: saveDrive

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
public void saveDrive(boolean night, boolean weather, boolean adverse, String driverId) {
    // Check if the user is signed in:
    boolean isSignedIn = FirebaseHelper.signInIfNeeded((MainActivity)getActivity());
    // Don't do anything if the user isn't signed in:
    if (!isSignedIn) return;
    // Delete the ongoing drive now that it's over:
    ongoingRef.removeValue();

    // Set the ending time so that startingTime-endingTime is exact in minutes:
    endingTime.set(Calendar.SECOND, startingTime.get(Calendar.SECOND));
    endingTime.set(Calendar.MILLISECOND, startingTime.get(Calendar.MILLISECOND));

    // Connect to the database
    DatabaseReference driveRef = FirebaseDatabase.getInstance().getReference().child(userId).child("times").push();
    driveRef.child("start").setValue(startingTime.getTimeInMillis());
    driveRef.child("end").setValue(endingTime.getTimeInMillis());
    driveRef.child("night").setValue(night);
    driveRef.child("weather").setValue(weather);
    driveRef.child("adverse").setValue(adverse);
    driveRef.child("driver_id").setValue(driverId);
}
 
開發者ID:brianjaustin,項目名稱:permitlog-android,代碼行數:22,代碼來源:HomeFragment.java

示例10: addChallengeCheckPoint

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
/**
 * Given the name of a challenge and one of its two users, adds one checkpoint its list, named after its
 * sequence number in the challenge.
 *
 * @param checkPoint        Checkpoint to add.
 * @param challengeName     Challenge to modify.
 * @param user              The user of the challenge to which to add data.
 * @param seqNumber         Sequence number of the checkpoint in the current challenge.
 */
public void addChallengeCheckPoint(CheckPoint checkPoint, String challengeName, String user, int seqNumber) {

    if (user == null || challengeName == null || checkPoint == null) {
        throw new IllegalArgumentException("Challenge node or data parameters can't be null");
    } else if (user.isEmpty() || challengeName.isEmpty()) {
        throw new IllegalArgumentException("Challenge node parameters can't be empty");
    }

    DatabaseReference checkPointRef = databaseReference.child(FirebaseNodes.CHALLENGES).child(challengeName).child(user)
            .child(FirebaseNodes.ChallengeStatus.DATA.toString()).child(Integer.toString(seqNumber));

    Map<String, Object> checkPointUpdate = new HashMap<>();
    checkPointUpdate.put("/" + FirebaseNodes.LATITUDE, checkPoint.getLatitude());
    checkPointUpdate.put("/" + FirebaseNodes.LONGITUDE, checkPoint.getLongitude());

    checkPointRef.updateChildren(checkPointUpdate);
}
 
開發者ID:IrrilevantHappyLlamas,項目名稱:Runnest,代碼行數:27,代碼來源:FirebaseHelper.java

示例11: push

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
public <T> Observable<T> push(final DatabaseReference databaseReference) {
    final Observable<T> observable = Observable.create(new Observable.OnSubscribe<T>() {
                                                           @Override
                                                           public void call(final Subscriber<? super T> subscriber) {
                                                               databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                                                                   @Override
                                                                   public void onDataChange(DataSnapshot dataSnapshot) {
                                                                       subscriber.onNext(null);
                                                                       subscriber.onCompleted();
                                                                   }

                                                                   @Override
                                                                   public void onCancelled(DatabaseError databaseError) {

                                                                   }
                                                               });
                                                           }
                                                       });

    databaseReference.push();
    return observable;
}
 
開發者ID:florent37,項目名稱:EasyFirebase,代碼行數:23,代碼來源:RxFirebaseHelper.java

示例12: subtractFromDistanceRemaining

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
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());
                }
            });
}
 
開發者ID:moizalicious,項目名稱:Forager,代碼行數:18,代碼來源:StartGame.java

示例13: testSubscribeThenUnsubscribeWithoutProblems

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
@Test
public void testSubscribeThenUnsubscribeWithoutProblems()
    throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  ValueEventListener listener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {}

        @Override
        public void onCancelled(DatabaseError error) {
          fail("Should not be cancelled");
        }
      };

  ValueEventListener listenerHandle = ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle);
  ZombieVerifier.verifyRepoZombies(ref);
  ValueEventListener listenerHandle2 = ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle2);
  ZombieVerifier.verifyRepoZombies(ref);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:26,代碼來源:EventTestIT.java

示例14: threadOn

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
public void threadOn(String threadId, Deferred<BThread, Void, Void> deferred){
    if (DEBUG) Timber.v("threadOn, EntityID: %s",threadId);
    if (!isListeningToThread(threadId))
    {
        threadsIds.add(threadId);

        final DatabaseReference threadRef = FirebasePaths.threadRef(threadId);

        // Add an observer to the thread details so we get
        // updated when the thread details change
        DatabaseReference detailsRef = threadRef.child(BFirebaseDefines.Path.BDetailsPath);

        FirebaseEventCombo combo = getCombo(threadId, detailsRef.toString(), new ThreadUpdateChangeListener(threadId, handlerThread, deferred));

        detailsRef.addValueEventListener(combo.getListener());
    }
    else if (DEBUG) Timber.e("Thread is already handled..");

}
 
開發者ID:MobileDev418,項目名稱:AndroidBackendlessChat,代碼行數:20,代碼來源:FirebaseEventsManager.java

示例15: updateComment

import com.google.firebase.database.DatabaseReference; //導入依賴的package包/類
public void updateComment(String commentId, String commentText, String postId, final OnTaskCompleteListener onTaskCompleteListener) {
    DatabaseReference mCommentReference = database.getReference().child("post-comments").child(postId).child(commentId).child("text");
    mCommentReference.setValue(commentText).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(true);
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(false);
            }
            LogUtil.logError(TAG, "updateComment", e);
        }
    });
}
 
開發者ID:rozdoum,項目名稱:social-app-android,代碼行數:20,代碼來源:DatabaseHelper.java


注:本文中的com.google.firebase.database.DatabaseReference類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。