Java Code Examples for com.google.firebase.database.DatabaseReference#addValueEventListener()
The following examples show how to use
com.google.firebase.database.DatabaseReference#addValueEventListener() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChatFragment.java From SnapchatClone with MIT License | 6 votes |
private void getUserInfo(String key) { DatabaseReference userDB = FirebaseDatabase.getInstance().getReference().child("users").child(key); userDB.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { String username = dataSnapshot.child("username").getValue().toString(); String profileImageUrl = dataSnapshot.child("profileImageUrl").getValue().toString(); String uid = dataSnapshot.getRef().getKey(); StoryObject obj = new StoryObject(username, uid, profileImageUrl,"chat"); if (!results.contains(obj)) { results.add(obj); adapter.notifyDataSetChanged(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); }
Example 2
Source File: OfflineActivity.java From snippets-android with Apache License 2.0 | 6 votes |
private void getServerTimeOffset() { // [START rtdb_server_time_offset] DatabaseReference offsetRef = FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset"); offsetRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { double offset = snapshot.getValue(Double.class); double estimatedServerTimeMs = System.currentTimeMillis() + offset; } @Override public void onCancelled(@NonNull DatabaseError error) { Log.w(TAG, "Listener was cancelled"); } }); // [END rtdb_server_time_offset] }
Example 3
Source File: DataTestIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@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 4
Source File: FirebaseCache.java From white-label-event-app with Apache License 2.0 | 6 votes |
private void warmEvent() { final DatabaseReference eventRef = fdb.getReference("/event"); eventRef.addValueEventListener(new ExecutorValueEventListener(executor) { @Override protected void onDataChangeExecutor(DataSnapshot data) { LOGGER.fine("New Event data"); event = FirebaseDatabaseHelpers.toEvent(data); bus.post(event); } @Override protected void onCancelledExecutor(DatabaseError databaseError) { LOGGER.log(Level.SEVERE, "Error reading event", databaseError.toException()); } }); }
Example 5
Source File: EventTestIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@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); }
Example 6
Source File: FirebaseCache.java From white-label-event-app with Apache License 2.0 | 6 votes |
private void warmSpeakers() { final DatabaseReference ref = fdb.getReference("/sections/speakers"); ref.addValueEventListener(new ExecutorValueEventListener(executor) { @Override public void onDataChangeExecutor(final DataSnapshot data) { LOGGER.fine("New Speaker data"); speakers = FirebaseDatabaseHelpers.toSpeakersSection(data); bus.post(speakers); } @Override public void onCancelledExecutor(final DatabaseError databaseError) { LOGGER.log(Level.SEVERE, "Error reading speakers", databaseError.toException()); } }); }
Example 7
Source File: PostInteractor.java From social-app-android with Apache License 2.0 | 6 votes |
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 8
Source File: PostInteractor.java From social-app-android with Apache License 2.0 | 5 votes |
public ValueEventListener getPost(final String id, final OnPostChangedListener listener) { DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY).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())); } }); databaseHelper.addActiveListener(valueEventListener, databaseReference); return valueEventListener; }
Example 9
Source File: AdapterListFeed.java From FeedFire with MIT License | 5 votes |
public void changeLikeImg(final String feedKey){ final DatabaseReference referenceLike = FirebaseDatabase.getInstance().getReference().child(MainActivity.LIKE_ROOT); final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser(); referenceLike.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { long totalLike = 0; for (DataSnapshot snapshot : dataSnapshot.getChildren()) { if (snapshot.getKey().equals(feedKey)) { totalLike = snapshot.getChildrenCount(); break; } } if (dataSnapshot.child(feedKey).hasChild(auth.getUid())){ // ta curtido ivLike.setImageResource( R.drawable.ic_thumb_up_blue_24dp ); }else{ // nao ta curtido ivLike.setImageResource( R.drawable.ic_thumb_up_grey600_24dp ); } tvLike.setText(totalLike+" likes"); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
Example 10
Source File: DisplayImageActivity.java From SnapchatClone with MIT License | 5 votes |
private void listenForStory() { DatabaseReference followingStoryDB = FirebaseDatabase.getInstance().getReference().child("users").child(uid); followingStoryDB.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String imgUrl = ""; long timestampBeg = 0, timestampEnd = 0; for (DataSnapshot storySnapshot : dataSnapshot.child("story").getChildren()) { if (storySnapshot.child("timestampBeg").getValue() != null) { timestampBeg = Long.parseLong(storySnapshot.child("timestampBeg").getValue().toString()); } if (storySnapshot.child("timestampEnd").getValue() != null) { timestampEnd = Long.parseLong(storySnapshot.child("timestampEnd").getValue().toString()); } if (storySnapshot.child("imageUrl").getValue() != null) { imgUrl = storySnapshot.child("imageUrl").getValue().toString(); } long currentTime = System.currentTimeMillis(); if (currentTime >= timestampBeg && currentTime <= timestampEnd) { imageUrlList.add(imgUrl); if (!started) { started = true; initializeDisplay(); } } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); }
Example 11
Source File: Capabilities.java From ChatApp with Apache License 2.0 | 5 votes |
@Override public void onCreate() { super.onCreate(); // For offline use FirebaseDatabase.getInstance().setPersistenceEnabled(true); Picasso.Builder builder = new Picasso.Builder(this); builder.downloader(new OkHttpDownloader(this, Integer.MAX_VALUE)); Picasso build = builder.build(); build.setLoggingEnabled(true); Picasso.setSingletonInstance(build); // If user disconnect if(FirebaseAuth.getInstance().getCurrentUser() != null) { final DatabaseReference userDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()); userDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot != null) { userDatabase.child("online").onDisconnect().setValue(ServerValue.TIMESTAMP); } } @Override public void onCancelled(DatabaseError databaseError) { Log.d(TAG, "usersDatabase failed: " + databaseError.getMessage()); } }); } }
Example 12
Source File: OrderByTestIT.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Test public void testRemovingDefaultListener() throws InterruptedException, ExecutionException, TimeoutException, TestFailure { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ; Object initialData = MapBuilder.of("key", "value"); new WriteFuture(ref, initialData).timedGet(); ValueEventListener listener = ref.orderByKey() .addValueEventListener( new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) {} @Override public void onCancelled(DatabaseError error) {} }); ref.addValueEventListener(listener); // Should remove both listener and should remove the listen sent to the server ref.removeEventListener(listener); // This used to crash because a listener for ref.orderByKey() existed already Object result = new ReadFuture(ref.orderByKey()).waitForLastValue(); assertEquals(initialData, result); }
Example 13
Source File: CommentInteractor.java From social-app-android with Apache License 2.0 | 5 votes |
public ValueEventListener getCommentsList(String postId, final OnDataChangedListener<Comment> onDataChangedListener) { DatabaseReference databaseReference = databaseHelper .getDatabaseReference() .child(DatabaseHelper.POST_COMMENTS_DB_KEY) .child(postId); ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<Comment> list = new ArrayList<>(); for (DataSnapshot snapshot : dataSnapshot.getChildren()) { Comment comment = snapshot.getValue(Comment.class); list.add(comment); } Collections.sort(list, (lhs, rhs) -> ((Long) rhs.getCreatedDate()).compareTo((Long) lhs.getCreatedDate())); onDataChangedListener.onListChanged(list); } @Override public void onCancelled(DatabaseError databaseError) { LogUtil.logError(TAG, "getCommentsList(), onCancelled", new Exception(databaseError.getMessage())); } }); databaseHelper.addActiveListener(valueEventListener, databaseReference); return valueEventListener; }
Example 14
Source File: OfflineActivity.java From snippets-android with Apache License 2.0 | 5 votes |
private void fullConnectionExample() { // [START rtdb_full_connection_example] // Since I can connect from multiple devices, we store each connection instance separately // any time that connectionsRef's value is null (i.e. has no children) I am offline final FirebaseDatabase database = FirebaseDatabase.getInstance(); final DatabaseReference myConnectionsRef = database.getReference("users/joe/connections"); // Stores the timestamp of my last disconnect (the last time I was seen online) final DatabaseReference lastOnlineRef = database.getReference("/users/joe/lastOnline"); final DatabaseReference connectedRef = database.getReference(".info/connected"); connectedRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { boolean connected = snapshot.getValue(Boolean.class); if (connected) { DatabaseReference con = myConnectionsRef.push(); // When this device disconnects, remove it con.onDisconnect().removeValue(); // When I disconnect, update the last time I was seen online lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP); // Add this device to my connections list // this value could contain info about the device or a timestamp too con.setValue(Boolean.TRUE); } } @Override public void onCancelled(DatabaseError error) { Log.w(TAG, "Listener was cancelled at .info/connected"); } }); // [END rtdb_full_connection_example] }
Example 15
Source File: PostInteractor.java From social-app-android with Apache License 2.0 | 5 votes |
public ValueEventListener getPost(final String id, final OnPostChangedListener listener) { DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY).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())); } }); databaseHelper.addActiveListener(valueEventListener, databaseReference); return valueEventListener; }
Example 16
Source File: StoryFragment.java From SnapchatClone with MIT License | 5 votes |
private void listenForData() { for (int i = 0; i < UserInformation.listFollowing.size(); i++) { DatabaseReference followingStoryDB = FirebaseDatabase.getInstance().getReference().child("users").child(UserInformation.listFollowing.get(i)); followingStoryDB.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String username = dataSnapshot.child("username").getValue().toString(); String profileImageUrl = dataSnapshot.child("profileImageUrl").getValue().toString(); String uid = dataSnapshot.getRef().getKey(); long timestampBeg = 0, timestampEnd = 0; for (DataSnapshot storySnapshot : dataSnapshot.child("story").getChildren()) { if (storySnapshot.child("timestampBeg").getValue() != null) { timestampBeg = Long.parseLong(storySnapshot.child("timestampBeg").getValue().toString()); } if (storySnapshot.child("timestampEnd").getValue() != null) { timestampEnd = Long.parseLong(storySnapshot.child("timestampEnd").getValue().toString()); } long currentTime = System.currentTimeMillis(); if (currentTime >= timestampBeg && currentTime <= timestampEnd) { StoryObject object = new StoryObject(username, uid, profileImageUrl,"story"); if (!results.contains(object)) { results.add(object); adapter.notifyDataSetChanged(); } } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
Example 17
Source File: MainActivity.java From snippets-android with Apache License 2.0 | 5 votes |
public void basicReadWrite() { // [START write_message] // Write a message to the database FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!"); // [END write_message] // [START read_message] // Read from the database myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. String value = dataSnapshot.getValue(String.class); Log.d(TAG, "Value is: " + value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } }); // [END read_message] }
Example 18
Source File: EventTestIT.java From firebase-admin-java with Apache License 2.0 | 4 votes |
@Test public void testUnsubscribeEventsAndConfirmEventsNoLongerFire() throws TestFailure, ExecutionException, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ; final AtomicInteger callbackCount = new AtomicInteger(0); final ValueEventListener listener = ref.addValueEventListener( new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { if (snapshot.getValue() != null) { callbackCount.incrementAndGet(); } } @Override public void onCancelled(DatabaseError error) { fail("Should not be cancelled"); } }); ZombieVerifier.verifyRepoZombies(ref); for (int i = 0; i < 3; ++i) { ref.setValueAsync(i); } TestHelpers.waitForRoundtrip(ref); ref.removeEventListener(listener); ZombieVerifier.verifyRepoZombies(ref); for (int i = 10; i < 13; ++i) { ref.setValueAsync(i); } for (int i = 20; i < 22; ++i) { ref.setValueAsync(i); } new WriteFuture(ref, 22).timedGet(); assertEquals(3, callbackCount.get()); }
Example 19
Source File: EventTestIT.java From firebase-admin-java with Apache License 2.0 | 4 votes |
@Test public void testRegisterTheSameCallbackMultipleTimes() throws TestFailure, ExecutionException, TimeoutException, InterruptedException { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ; final AtomicInteger callbackCount = new AtomicInteger(0); ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { if (snapshot.getValue() != null) { callbackCount.incrementAndGet(); } } @Override public void onCancelled(DatabaseError error) { fail("Should not be cancelled"); } }; ref.addValueEventListener(listener); ref.addValueEventListener(listener); ref.addValueEventListener(listener); ZombieVerifier.verifyRepoZombies(ref); new WriteFuture(ref, 42).timedGet(); assertEquals(3, callbackCount.get()); ref.removeEventListener(listener); new WriteFuture(ref, 84).timedGet(); assertEquals(5, callbackCount.get()); ZombieVerifier.verifyRepoZombies(ref); ref.removeEventListener(listener); new WriteFuture(ref, 168).timedGet(); assertEquals(6, callbackCount.get()); ZombieVerifier.verifyRepoZombies(ref); ref.removeEventListener(listener); new WriteFuture(ref, 376).timedGet(); assertEquals(6, callbackCount.get()); ZombieVerifier.verifyRepoZombies(ref); }
Example 20
Source File: ViewReports.java From Crimson with Apache License 2.0 | 3 votes |
private void getReports() { FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference reportsReference = database.getReference("reports"); allReports = new ArrayList<>(); reportsReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { AllReports reports; for (DataSnapshot postSnapshot: snapshot.getChildren()) { String value = String.valueOf(postSnapshot.getValue()); reports = new AllReports(); reports.setUrl(value); allReports.add(reports); } showImages(allReports); } @Override public void onCancelled(DatabaseError databaseError) { Log.e("The read failed: " ,databaseError.getMessage()); } }); }