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


Java DatabaseReference.child方法代碼示例

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


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

示例1: 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

示例2: testMultipleWriteValuesReconnectRead

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

示例3: getMembersFromDatabase

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private void getMembersFromDatabase() {
    DatabaseReference mDatabaseReference = mFirebaseDatabase.getReference();
    DatabaseReference membersDir = mDatabaseReference.child(MEMBERS_PATH);

    ArrayList<Member> members = new ArrayList<>();

    membersDir.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            membersDir.removeEventListener(this);
            for (DataSnapshot memberSnapshot : dataSnapshot.getChildren()) {
                Member member = memberSnapshot.getValue(Member.class);
                members.add(member);
            }

            mMemberAdapter.swapData(members);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // NOT IMPLEMENTED
        }
    });
}
 
開發者ID:codingdojoangola,項目名稱:cda-app,代碼行數:25,代碼來源:MembersFragment.java

示例4: insertFakeData

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
private void insertFakeData() {
    DatabaseReference mDatabaseReference = mFirebaseDatabase.getReference();
    DatabaseReference membersDir = mDatabaseReference.child("members");

    ArrayList<Member.Disponibility> disponibilities = new ArrayList<Member.Disponibility>();
    disponibilities.add(Member.Disponibility.FULL_TIME);
    disponibilities.add(Member.Disponibility.FREELANCER);

    ArrayList<String> programmingLangs = new ArrayList<>();
    programmingLangs.add("C#");
    programmingLangs.add("C++");
    programmingLangs.add("Java");

    ArrayList<String> technologies = new ArrayList<>();
    technologies.add("ASP.NET");
    technologies.add("WPF");

    String id = membersDir.push().getKey();
    Member member = new Member(id, "Henrick Kakutalua", Member.BeltColor.WHITE, disponibilities,
            12, programmingLangs, technologies,
            "https://avatars2.githubusercontent.com/u/4200487?s=400&v=4");

    membersDir.child(id).setValue(member);
}
 
開發者ID:codingdojoangola,項目名稱:cda-app,代碼行數:25,代碼來源:MembersFragment.java

示例5: 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

示例6: testStillAuthenticatedAfterReconnect

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

示例7: addOrUpdateUser

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
/**
 * Add a new user to the firebase remote database. If the user already exists on the database, update his name.
 *
 * @param name   The name of the user.
 * @param email  The id associated to the user.
 * @throws IllegalArgumentException     if the arguments are <code>null</code> or empty
 */
public void addOrUpdateUser(String name, String email) {

    //Check validity of arguments
    if(name == null || email == null) {
        throw new IllegalArgumentException("Name and email for user have to be non-null");
    }
    if(name.isEmpty() || email.isEmpty() || email.length() > 100) {
        throw new IllegalArgumentException("Name and email for user must be non empty and " +
                "email length has to be under 100 characters.");
    }

    final DatabaseReference user = databaseReference.child(FirebaseNodes.USERS).child(getFireBaseMail(email));
    user.child(FirebaseNodes.NAME).setValue(name);

    final DatabaseReference statistics = user.child(FirebaseNodes.STATISTICS);
    statistics.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!dataSnapshot.exists()) {
                Map<String, Object> statisticsUpload = new HashMap<>();
                statisticsUpload.put("/" + FirebaseNodes.TOTAL_RUNNING_TIME, 0);
                statisticsUpload.put("/" + FirebaseNodes.TOTAL_RUNNING_DISTANCE, 0);
                statisticsUpload.put("/" + FirebaseNodes.TOTAL_NUMBER_OF_RUNS, 0);
                statisticsUpload.put("/" + FirebaseNodes.TOTAL_NUMBER_OF_CHALLENGES, 0);
                statisticsUpload.put("/" + FirebaseNodes.TOTAL_NUMBER_OF_WON_CHALLENGES, 0);
                statisticsUpload.put("/" + FirebaseNodes.TOTAL_NUMBER_OF_LOST_CHALLENGES, 0);

                statistics.updateChildren(statisticsUpload);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
}
 
開發者ID:IrrilevantHappyLlamas,項目名稱:Runnest,代碼行數:44,代碼來源:FirebaseHelper.java

示例8: testParentForRootAndNonRootLocations

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

示例9: testKeptSyncedChild

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

示例10: parseEvent

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

示例11: testUseFallbackThenDefineIndex

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

示例12: testWriteLeafNodeRemoveParentWaitForEvents

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
@Test
@Ignore
public void testWriteLeafNodeRemoveParentWaitForEvents()
    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").removeValueAsync();
  assertTrue(writeHelper.waitForEvents());
  assertTrue(readHelper.waitForEvents());
  writeHelper.cleanup();
  readHelper.cleanup();

  // Make sure we actually have null there now
  assertNull(TestHelpers.getSnap(reader).getValue());
  assertNull(TestHelpers.getSnap(writer).getValue());

  ReadFuture readFuture = ReadFuture.untilNonNull(reader);

  ReadFuture writeFuture = ReadFuture.untilNonNull(writer);

  writer.child("a/aa").setValueAsync(3.1415);

  List<EventRecord> readerEvents = readFuture.timedGet();
  List<EventRecord> writerEvents = writeFuture.timedGet();

  DataSnapshot readerSnap = readerEvents.get(readerEvents.size() - 1).getSnapshot();
  readerSnap = readerSnap.child("a/aa");
  assertEquals(3.1415, readerSnap.getValue());

  DataSnapshot writerSnap = writerEvents.get(writerEvents.size() - 1).getSnapshot();
  writerSnap = writerSnap.child("a/aa");
  assertEquals(3.1415, writerSnap.getValue());
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:66,代碼來源:DataTestIT.java

示例13: getAllPlantsReference

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
public DatabaseReference getAllPlantsReference() {
    DatabaseReference userRef = getUserReference();
    return userRef == null ? null : userRef.child("plants");
}
 
開發者ID:iskandergaba,項目名稱:Botanist,代碼行數:5,代碼來源:DatabaseManager.java

示例14: getPlantReference

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
public DatabaseReference getPlantReference(String plantId) {
    DatabaseReference plantsRef = getAllPlantsReference();
    return plantsRef == null ? null : plantsRef.child(plantId);
}
 
開發者ID:iskandergaba,項目名稱:Botanist,代碼行數:5,代碼來源:DatabaseManager.java

示例15: makeMeOnline

import com.google.firebase.database.DatabaseReference; //導入方法依賴的package包/類
public final void makeMeOnline() {
    if (Constants._DEVELOP_MODE)
        return;

    if (contact == null) {
        showLog("BaseActivity - contact is null.");
        contact = new Contact();
        contact.setOnline(true);
        contact.setUserId(PrefsHelper.getId());
        contact.setUsername(PrefsHelper.getName());
        contact.setUserUrlPhoto(PrefsHelper.getPhoto());
    }

    if (FirebaseAuth.getInstance().getCurrentUser() == null) return;

    final DatabaseReference userPresence = Library.getAllUsersChatsRef().child(contact.getUserId());
    final DatabaseReference lastOnlineRef = userPresence.child("lastOnline");
    final DatabaseReference onlineRef = userPresence.child("online");

    amOnline = FirebaseDatabase.getInstance().getReference(".info/connected");
    onlineStatusListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            // If user is connected, set online
            if (dataSnapshot.getValue(Boolean.class)) {
                showLog("handleUserPresence - onDataChange - use is connected");
                showLog("handleUserPresence - onDataChange - setting online...");
                userPresence.setValue(contact);
                // When the user will be disconnected it will set the user offline
                lastOnlineRef.onDisconnect().setValue(System.currentTimeMillis());
                onlineRef.onDisconnect().setValue(Boolean.FALSE);
                showLog("handleUserPresence - onDataChange - setting online - done.");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            showLog("Presence Listener - user offline");
        }
    };

    amOnline.addValueEventListener(onlineStatusListener);
}
 
開發者ID:pedromassango,項目名稱:Programmers,代碼行數:46,代碼來源:BaseActivity.java


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