本文整理汇总了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) {
}
});
}
示例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();
}
});
}
示例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();
}
}
示例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);
}
}
示例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;
}
示例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;
}
示例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);
}
示例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();
}
示例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);
}
示例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);
}
示例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;
}
示例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());
}
});
}
示例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);
}
示例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..");
}
示例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);
}
});
}