Java Code Examples for com.google.firebase.database.DatabaseReference#child()
The following examples show how to use
com.google.firebase.database.DatabaseReference#child() .
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: RestorePresenter.java From FastAccess with GNU General Public License v3.0 | 6 votes |
@Override public void onRestore(@NonNull DatabaseReference databaseReference, @Nullable String userId) { this.userId = userId; FirebaseUser user = getView().user(); if (InputHelper.isEmpty(userId)) { if (user != null) userId = user.getUid(); } if (InputHelper.isEmpty(userId)) { getView().onShowMessage(R.string.login_first_msg); getView().finishOnError(); } else { getView().onShowProgress(); Query query = databaseReference .child(userId); query.keepSynced(true); query.addListenerForSingleValueEvent(this); } }
Example 2
Source File: PersistenceTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@Test public void deepUpdateTest() throws Throwable { PersistenceManager manager = newTestPersistenceManager(); DatabaseConfig cfg1 = newFrozenTestConfig(); DatabaseReference ref1 = refWithConfig(cfg1, manager).push(); goOffline(cfg1); Map<String, Object> updates = new HashMap<String, Object>(); updates.put("foo/deep/update", "bar"); ref1.updateChildren(updates); waitForQueue(ref1); DatabaseConfig cfg2 = newFrozenTestConfig(); DatabaseReference ref2 = refWithConfig(cfg2, manager); ref2 = ref2.child(ref1.getKey()); Object value = new ReadFuture(ref2).waitForLastValue(); assertEquals(value, fromSingleQuotedString("{ 'foo': { 'deep': { 'update': 'bar' } } }")); }
Example 3
Source File: DataTestIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Test public void testMultipleWriteValuesReconnectRead() throws ExecutionException, TimeoutException, InterruptedException, TestFailure { List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2); final DatabaseReference writer = refs.get(0); final DatabaseReference reader = refs.get(1); writer.child("a").child("b").child("c").setValueAsync(1); writer.child("a").child("d").child("e").setValueAsync(2); writer.child("a").child("d").child("f").setValueAsync(3); WriteFuture writeFuture = new WriteFuture(writer.child("g"), 4); writeFuture.timedGet(); Map<String, Object> expected = new MapBuilder() .put("a", new MapBuilder().put("b", new MapBuilder().put("c", 1L).build()) .put("d", new MapBuilder().put("e", 2L).put("f", 3L).build()).build()) .put("g", 4L).build(); ReadFuture readFuture = new ReadFuture(reader); GenericTypeIndicator<Map<String, Object>> t = new GenericTypeIndicator<Map<String, Object>>() { }; Map<String, Object> result = readFuture.timedGet().get(0).getSnapshot().getValue(t); TestHelpers.assertDeepEquals(expected, result); }
Example 4
Source File: RulesTestIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@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); } }
Example 5
Source File: Utility.java From stockita-point-of-sale with MIT License | 5 votes |
/** * Create new user profile into Firebase location users * * @param userName The user name * @param userUID The user UID from Firebase Auth * @param userEmail The user encoded email */ public static void createUser(Context context, String userName, String userUID, String userEmail, String userPhoto) { // Encoded the email that the user just signed in with String encodedUserEmail = Utility.encodeEmail(userEmail); // This is the Firebase server value time stamp HashMap HashMap<String, Object> timestampCreated = new HashMap<>(); // Pack the ServerValue.TIMESTAMP into a HashMap timestampCreated.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP); /** * Pass those data into java object */ UserModel userModel = new UserModel(userName, userUID, userEmail, userPhoto, timestampCreated); /** * Initialize the DatabaseReference */ DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(); /** * Get reference into the users location */ DatabaseReference usersLocation = databaseReference.child(Constants.FIREBASE_USER_LOCATION); /** * Add the user object into the users location in Firebase database */ usersLocation.child(userUID).setValue(userModel); }
Example 6
Source File: SyncPointTest.java From firebase-admin-java with Apache License 2.0 | 5 votes |
private static TestEvent parseEvent( DatabaseReference ref, Map<String, Object> eventSpec, String basePath) { String path = (String) eventSpec.get("path"); Event.EventType type; String eventTypeStr = (String) eventSpec.get("type"); if (eventTypeStr.equals("value")) { type = Event.EventType.VALUE; } else if (eventTypeStr.equals("child_added")) { type = Event.EventType.CHILD_ADDED; } else if (eventTypeStr.equals("child_moved")) { type = Event.EventType.CHILD_MOVED; } else if (eventTypeStr.equals("child_removed")) { type = Event.EventType.CHILD_REMOVED; } else if (eventTypeStr.equals("child_changed")) { type = Event.EventType.CHILD_CHANGED; } else { throw new RuntimeException("Unknown event type: " + eventTypeStr); } String childName = (String) eventSpec.get("name"); String prevName = eventSpec.get("prevName") != null ? (String) eventSpec.get("prevName") : null; Object data = eventSpec.get("data"); DatabaseReference rootRef = basePath != null ? ref.getRoot().child(basePath) : ref.getRoot(); DatabaseReference pathRef = rootRef.child(path); if (childName != null) { pathRef = pathRef.child(childName); } Node node = NodeUtilities.NodeFromJSON(data); // TODO: don't use priority index by default DataSnapshot snapshot = InternalHelpers.createDataSnapshot(pathRef, IndexedNode.from(node)); return new TestEvent(type, snapshot, prevName, null); }
Example 7
Source File: KeepSyncedTestIT.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Test public void testKeptSyncedChild() throws Exception { DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp); DatabaseReference child = ref.child("random-child"); ref.keepSynced(true); try { assertIsKeptSynced(child); } finally { // cleanup ref.keepSynced(false); } }
Example 8
Source File: DataTestIT.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Test public void testParentForRootAndNonRootLocations() throws DatabaseException { DatabaseReference ref = FirebaseDatabase.getInstance(masterApp).getReference(); assertNull(ref.getParent()); DatabaseReference child = ref.child("a"); assertEquals(ref, child.getParent()); child = ref.child("a/b/c"); assertEquals(ref, child.getParent().getParent().getParent()); }
Example 9
Source File: FirebaseSaveObject.java From Examples with MIT License | 5 votes |
/** * Save item object in Firebase. * @param item */ private void save(Item item) { if (item != null) { initFirebase(); /* Get database root reference */ DatabaseReference databaseReference = firebaseDatabase.getReference("/"); /* Get existing child or will be created new child. */ DatabaseReference childReference = databaseReference.child("item"); /** * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting. * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value * using `countDownLatch.countDown()` and application will continues its execution. */ CountDownLatch countDownLatch = new CountDownLatch(1); childReference.setValue(item, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError de, DatabaseReference dr) { System.out.println("Record saved!"); // decrement countDownLatch value and application will be continues its execution. countDownLatch.countDown(); } }); try { //wait for firebase to saves record. countDownLatch.await(); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
Example 10
Source File: RulesTestIT.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Test public void testStillAuthenticatedAfterReconnect() throws InterruptedException, ExecutionException, TestFailure, TimeoutException { DatabaseConfig config = TestHelpers.getDatabaseConfig(masterApp); DatabaseReference root = FirebaseDatabase.getInstance(masterApp).getReference(); DatabaseReference ref = root.child(writer.getPath().toString()); RepoManager.interrupt(config); RepoManager.resume(config); DatabaseError err = new WriteFuture(ref.child("any_auth"), true).timedGet(); assertNull(err); }
Example 11
Source File: SyncPointTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
private static TestEvent parseEvent( DatabaseReference ref, Map<String, Object> eventSpec, String basePath) { String path = (String) eventSpec.get("path"); Event.EventType type; String eventTypeStr = (String) eventSpec.get("type"); if (eventTypeStr.equals("value")) { type = Event.EventType.VALUE; } else if (eventTypeStr.equals("child_added")) { type = Event.EventType.CHILD_ADDED; } else if (eventTypeStr.equals("child_moved")) { type = Event.EventType.CHILD_MOVED; } else if (eventTypeStr.equals("child_removed")) { type = Event.EventType.CHILD_REMOVED; } else if (eventTypeStr.equals("child_changed")) { type = Event.EventType.CHILD_CHANGED; } else { throw new RuntimeException("Unknown event type: " + eventTypeStr); } String childName = (String) eventSpec.get("name"); String prevName = eventSpec.get("prevName") != null ? (String) eventSpec.get("prevName") : null; Object data = eventSpec.get("data"); DatabaseReference rootRef = basePath != null ? ref.getRoot().child(basePath) : ref.getRoot(); DatabaseReference pathRef = rootRef.child(path); if (childName != null) { pathRef = pathRef.child(childName); } Node node = NodeUtilities.NodeFromJSON(data); // TODO: don't use priority index by default DataSnapshot snapshot = InternalHelpers.createDataSnapshot(pathRef, IndexedNode.from(node)); return new TestEvent(type, snapshot, prevName, null); }
Example 12
Source File: KeepSyncedTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void childIsKeptSynced() throws Exception { DatabaseReference ref = IntegrationTestHelpers.getRandomNode(); DatabaseReference child = ref.child("random-child"); ref.keepSynced(true); assertIsKeptSynced(child); // cleanup ref.keepSynced(false); }
Example 13
Source File: FirebasePushObject.java From Examples with MIT License | 5 votes |
/** * Save item object in Firebase. * @param item */ private void saveUsingPush(Item item) { if (item != null) { initFirebase(); /* Get database root reference */ DatabaseReference databaseReference = firebaseDatabase.getReference("/"); /* Get existing child or will be created new child. */ DatabaseReference childReference = databaseReference.child("items"); /** * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting. * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value * using `countDownLatch.countDown()` and application will continues its execution. */ CountDownLatch countDownLatch = new CountDownLatch(1); /** * push() * Add to a list of data in the database. Every time you push a new node onto a list, * your database generates a unique key, like items/unique-item-id/data */ childReference.push().setValue(item, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError de, DatabaseReference dr) { System.out.println("Record saved!"); // decrement countDownLatch value and application will be continues its execution. countDownLatch.countDown(); } }); try { //wait for firebase to saves record. countDownLatch.await(); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
Example 14
Source File: NotificationChannel.java From Shipr-Community-Android with GNU General Public License v3.0 | 5 votes |
public NotificationChannel(Context context, DatabaseReference reference, String channel_Id, int channel_no) { this.context = context; this.channel_Id = channel_Id; this.reference = reference.child(channel_Id); String channel_Key = context.getString(R.string.shared_preference_key) + channel_Id; sharedPreferences = context.getSharedPreferences(channel_Key, Context.MODE_PRIVATE); count = sharedPreferences.getInt("count", 0); id = channel_no; messages = new ArrayList<>(); notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); }
Example 15
Source File: RoomManager.java From justaline-android with Apache License 2.0 | 5 votes |
/** * Default constructor for the FirebaseManager class. * * @param context The application context. */ public RoomManager(Context context) { app = FirebaseApp.initializeApp(context); if (app != null) { final DatabaseReference rootRef = FirebaseDatabase.getInstance(app).getReference(); roomsListRef = rootRef.child(ROOT_FIREBASE_ROOMS); DatabaseReference.goOnline(); } else { Log.d(TAG, "Could not connect to Firebase Database!"); roomsListRef = null; } }
Example 16
Source File: OrderByTestIT.java From firebase-admin-java with Apache License 2.0 | 4 votes |
@Test public void testUseFallbackThenDefineIndex() throws InterruptedException, ExecutionException, TimeoutException, TestFailure, IOException { DatabaseReference writer = IntegrationTestUtils.getRandomNode(masterApp) ; DatabaseReference readerReference = FirebaseDatabase.getInstance(masterApp).getReference(); DatabaseReference reader = readerReference.child(writer.getPath().toString()); Map<String, Object> foo1 = TestHelpers.fromJsonString( "{ " + "\"a\": {\"order\": 2, \"foo\": 1}, " + "\"b\": {\"order\": 0}, " + "\"c\": {\"order\": 1, \"foo\": false}, " + "\"d\": {\"order\": 3, \"foo\": \"hello\"} }"); new WriteFuture(writer, foo1).timedGet(); final List<DataSnapshot> snapshots = new ArrayList<>(); final Semaphore semaphore = new Semaphore(0); Query query = reader.orderByChild("order").limitToLast(2); final ValueEventListener listener = query.addValueEventListener( new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { snapshots.add(snapshot); semaphore.release(); } @Override public void onCancelled(DatabaseError error) { Assert.fail(); } }); TestHelpers.waitFor(semaphore); Assert.assertEquals(1, snapshots.size()); Map<String, Object> expected = MapBuilder.of( "d", MapBuilder.of("order", 3L, "foo", "hello"), "a", MapBuilder.of("order", 2L, "foo", 1L)); Assert.assertEquals(expected, snapshots.get(0).getValue()); uploadRules(masterApp, formatRules(reader, "{ \".indexOn\": \"order\" }")); Map<String, Object> fooE = TestHelpers.fromJsonString("{\"order\": 1.5, \"foo\": true}"); new WriteFuture(writer.child("e"), fooE).timedGet(); TestHelpers.waitForRoundtrip(reader); Map<String, Object> fooF = TestHelpers.fromJsonString("{\"order\": 4, \"foo\": {\"bar\": \"baz\"}}"); new WriteFuture(writer.child("f"), fooF).timedGet(); TestHelpers.waitForRoundtrip(reader); TestHelpers.waitFor(semaphore); Assert.assertEquals(2, snapshots.size()); Map<String, Object> expected2 = new MapBuilder() .put( "f", new MapBuilder() .put("order", 4L) .put("foo", MapBuilder.of("bar", "baz")) .build()) .put("d", MapBuilder.of("order", 3L, "foo", "hello")) .build(); Assert.assertEquals(expected2, snapshots.get(1).getValue()); // cleanup TestHelpers.waitForRoundtrip(reader); reader.removeEventListener(listener); }
Example 17
Source File: DataTestIT.java From firebase-admin-java with Apache License 2.0 | 4 votes |
@Test @Ignore public void testWriteLeafNodeRemoveLeafNodeWaitForEvents() throws InterruptedException, TimeoutException, TestFailure, ExecutionException { List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2); DatabaseReference reader = refs.get(0); DatabaseReference writer = refs.get(1); EventHelper writeHelper = new EventHelper().addValueExpectation(writer.child("a/aa")) .addChildExpectation(writer.child("a"), Event.EventType.CHILD_ADDED, "aa") .addValueExpectation(writer.child("a")) .addChildExpectation(writer, Event.EventType.CHILD_ADDED, "a").addValueExpectation(writer) .startListening(true); WriteFuture w = new WriteFuture(writer.child("a/aa"), 42); assertTrue(writeHelper.waitForEvents()); w.timedGet(); EventHelper readHelper = new EventHelper().addValueExpectation(reader.child("a/aa")) .addChildExpectation(reader.child("a"), Event.EventType.CHILD_ADDED, "aa") .addValueExpectation(reader.child("a")) .addChildExpectation(reader, Event.EventType.CHILD_ADDED, "a").addValueExpectation(reader) .startListening(); assertTrue(readHelper.waitForEvents()); readHelper.addValueExpectation(reader.child("a/aa")) .addChildExpectation(reader.child("a"), Event.EventType.CHILD_REMOVED, "aa") .addValueExpectation(reader.child("a")) .addChildExpectation(reader, Event.EventType.CHILD_REMOVED, "a").addValueExpectation(reader) .startListening(); writeHelper.addValueExpectation(reader.child("a/aa")) .addChildExpectation(reader.child("a"), Event.EventType.CHILD_REMOVED, "aa") .addValueExpectation(reader.child("a")) .addChildExpectation(reader, Event.EventType.CHILD_REMOVED, "a").addValueExpectation(reader) .startListening(); writer.child("a/aa").removeValueAsync(); assertTrue(writeHelper.waitForEvents()); assertTrue(readHelper.waitForEvents()); writeHelper.cleanup(); readHelper.cleanup(); DataSnapshot readerSnap = TestHelpers.getSnap(reader); assertNull(readerSnap.getValue()); DataSnapshot writerSnap = TestHelpers.getSnap(writer); assertNull(writerSnap.getValue()); readerSnap = TestHelpers.getSnap(reader.child("a/aa")); assertNull(readerSnap.getValue()); writerSnap = TestHelpers.getSnap(writer.child("a/aa")); assertNull(writerSnap.getValue()); ReadFuture readFuture = ReadFuture.untilNonNull(reader); ReadFuture writeFuture = ReadFuture.untilNonNull(writer); writer.child("a/aa").setValueAsync(3.1415); final List<EventRecord> readerEvents = readFuture.timedGet(); final List<EventRecord> writerEvents = writeFuture.timedGet(); readerSnap = readerEvents.get(readerEvents.size() - 1).getSnapshot(); readerSnap = readerSnap.child("a/aa"); assertEquals(3.1415, readerSnap.getValue()); writerSnap = writerEvents.get(writerEvents.size() - 1).getSnapshot(); writerSnap = writerSnap.child("a/aa"); assertEquals(3.1415, writerSnap.getValue()); }
Example 18
Source File: SaveFirebaseInstanceIdService.java From chat21-android-sdk with GNU Affero General Public License v3.0 | 4 votes |
@Override public void onTokenRefresh() { super.onTokenRefresh(); Log.d(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh"); String token = FirebaseInstanceId.getInstance().getToken(); Log.d(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh:" + " called with instanceId: " + token); Log.i(TAG_TOKEN, "SaveFirebaseInstanceIdService: token == " + token); FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); String appId = ChatManager.Configuration.appId; if (firebaseUser != null && StringUtils.isValid(appId)) { DatabaseReference root; if (StringUtils.isValid(ChatManager.Configuration.firebaseUrl)) { root = FirebaseDatabase.getInstance() .getReferenceFromUrl(ChatManager.Configuration.firebaseUrl); } else { root = FirebaseDatabase.getInstance().getReference(); } DatabaseReference firebaseUsersPath = root .child("apps/" + ChatManager.Configuration.appId + "/users/" + firebaseUser.getUid() + "/instances/" + token); Map<String, Object> device = new HashMap<>(); device.put("device_model", ChatUtils.getDeviceModel()); device.put("platform", "Android"); device.put("platform_version", ChatUtils.getSystemVersion()); device.put("language", ChatUtils.getSystemLanguage(getResources())); firebaseUsersPath.setValue(device); // placeholder value Log.i(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh: " + "saved with token: " + token + ", appId: " + appId + ", firebaseUsersPath: " + firebaseUsersPath); } else { Log.i(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh:" + "user is null. token == " + token + ", appId == " + appId); } }
Example 19
Source File: RepoDatabase.java From TvAppRepo with Apache License 2.0 | 4 votes |
public static void getLeanbackShortcut(String packageName, final LeanbackShortcutCallback callback) { final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference reference = database.getReference("leanbackShortcuts"); DatabaseReference shortcutReference = reference.child(packageName.replaceAll("[.]", "_")); if (DEBUG) { Log.d(TAG, "Looking at shortcut reference " + shortcutReference.toString()); Log.d(TAG, "Looking for package " + packageName); } shortcutReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (DEBUG) { Log.d(TAG, "Got value back " + dataSnapshot.toString()); } try { LeanbackShortcut leanbackShortcut = dataSnapshot.getValue(LeanbackShortcut.class); if (leanbackShortcut == null) { if (DEBUG) { Log.i(TAG, "No leanback shortcut"); } callback.onNoLeanbackShortcut(); return; } if (DEBUG) { Log.i(TAG, "This is a leanback shortcut"); } callback.onLeanbackShortcut(leanbackShortcut); } catch (Exception e) { if (DEBUG) { Log.i(TAG, "No leanback shortcut"); Log.e(TAG, e.getMessage()); } callback.onNoLeanbackShortcut(); } } @Override public void onCancelled(DatabaseError databaseError) { if (DEBUG) { Log.e(TAG, databaseError.toString()); } callback.onDatabaseError(databaseError); } }); }
Example 20
Source File: GlobalRoomManager.java From justaline-android with Apache License 2.0 | 4 votes |
@Override public boolean joinRoom(final RoomData roomData, final String uid, final boolean isPairing, final PartnerListener partnerListener, final PartnerDetectionListener partnerDetectionListener) { isHost = false; this.isPairing = isPairing; final DatabaseReference rootRef = FirebaseDatabase.getInstance(app).getReference(); globalRoomRef = rootRef.child(ROOT_GLOBAL_ROOM + "_" + globalRoomName); globalRoomRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String roomKey = dataSnapshot.getValue(String.class); Log.d(TAG, "received room key: " + roomKey); // Create a room if no global room is specified if (roomKey == null) { createRoom(uid, new RoomManager.StoreOperationListener() { @Override public void onRoomCreated(RoomData room, DatabaseError error) { globalRoomRef.setValue(room.key); } }, partnerListener); } else { mRoomData = new RoomData(roomKey, System.currentTimeMillis()); joinRoomInternal(roomKey, uid, partnerListener, partnerDetectionListener); if (globalRoomListener != null) { globalRoomListener.roomDataReady(); } } } @Override public void onCancelled(DatabaseError databaseError) { // TODO: handle cancelled event } }); return true; }