Java Code Examples for com.google.firebase.database.DatabaseReference#setValue()
The following examples show how to use
com.google.firebase.database.DatabaseReference#setValue() .
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: GeoFire.java From geofire-java with MIT License | 6 votes |
/** * Sets the location for a given key. * * @param key The key to save the location for * @param location The location of this key * @param completionListener A listener that is called once the location was successfully saved on the server or an * error occurred */ public void setLocation(final String key, final GeoLocation location, final CompletionListener completionListener) { if (key == null) { throw new NullPointerException(); } DatabaseReference keyRef = this.getDatabaseRefForKey(key); GeoHash geoHash = new GeoHash(location); Map<String, Object> updates = new HashMap<>(); updates.put("g", geoHash.getGeoHashString()); updates.put("l", Arrays.asList(location.latitude, location.longitude)); if (completionListener != null) { keyRef.setValue(updates, geoHash.getGeoHashString(), new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { completionListener.onComplete(key, databaseError); } }); } else { Object priority = geoHash.getGeoHashString(); keyRef.setValueAsync(updates, priority); } }
Example 2
Source File: GeoFire.java From geofire-java with MIT License | 6 votes |
/** * Removes the location for a key from this GeoFire. * * @param key The key to remove from this GeoFire * @param completionListener A completion listener that is called once the location is successfully removed * from the server or an error occurred */ public void removeLocation(final String key, final CompletionListener completionListener) { if (key == null) { throw new NullPointerException(); } DatabaseReference keyRef = this.getDatabaseRefForKey(key); if (completionListener != null) { keyRef.setValue(null, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { completionListener.onComplete(key, databaseError); } }); } else { keyRef.removeValueAsync(); } }
Example 3
Source File: KeepSyncedTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@Test public void keepSyncedNoDoesNotAffectExistingListener() throws Exception { DatabaseReference ref = IntegrationTestHelpers.getRandomNode(); ref.keepSynced(true); assertIsKeptSynced(ref); ReadFuture readFuture = new ReadFuture( ref, new ReadFuture.CompletionCondition() { @Override public boolean isComplete(List<EventRecord> events) { return events.get(events.size() - 1).getSnapshot().getValue().equals("done"); } }); // cleanup ref.keepSynced(false); // Should trigger our listener. ref.setValue("done"); readFuture.timedGet(); }
Example 4
Source File: DatabaseTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@Test public void setValueShouldFailWithPermissionDenied() throws Exception { FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseDatabase database = FirebaseDatabase.getInstance(); auth.signOut(); Thread.sleep(1000); // TODO(allisonbm92): Introduce a better way to reduce flakiness. DatabaseReference doc = database.getReference("restaurants").child(TestId.create()); HashMap<String, Object> data = new HashMap<>(); data.put("location", "Google DUB"); try { Task<?> setTask = doc.setValue(new HashMap<>(data)); Tasks2.waitForFailure(setTask); // Unfortunately, there's no good way to test that this has the correct error code, because // Database does not expose it through the task interface. Perhaps we could re-structure this // in the future. } finally { Tasks2.waitBestEffort(doc.removeValue()); } }
Example 5
Source File: Employee.java From Walk-In-Clinic-Android-App with MIT License | 5 votes |
public void update(){ try{ DatabaseReference dR = databaseUsers.child(id); DataBaseUser usr = new DataBaseUser(id, name, username, password, getRole()); usr.setClinicId(getClinicId()); usr.setCloseHours(closeHours); usr.setOpenHours(openHours); usr.setNotWorkingDays(notWorkingDays); dR.setValue(usr); }catch (Exception ex){ throw new IllegalArgumentException("Clinic doesn't exist"); } }
Example 6
Source File: ChatActivity.java From TinderClone with MIT License | 5 votes |
private void sendMessage() { String sendMessageText = mSendEditText.getText().toString(); if(!sendMessageText.isEmpty()){ DatabaseReference newMessageDb = mDatabaseChat.push(); Map newMessage = new HashMap(); newMessage.put("createdByUser", currentUserID); newMessage.put("text", sendMessageText); newMessageDb.setValue(newMessage); } mSendEditText.setText(null); }
Example 7
Source File: MyEmailer.java From quickstart-java with Apache License 2.0 | 5 votes |
public static void sendWeeklyEmail(Map<String,User> users, List<Post> topPosts) { // TODO(developer): send email to each user notifying them about the current top posts System.out.println("sendWeeklyEmail: MOCK IMPLEMENTATION"); System.out.println("sendWeeklyEmail: there are " + users.size() + " total users."); System.out.println("sendWeeklyEmail: the top post is " + topPosts.get(0).title + " by " + topPosts.get(0).author); for (String userId : users.keySet()) { // Mark the last time the weekly email was sent out // [START basic_write] DatabaseReference userRef = FirebaseDatabase.getInstance().getReference() .child("users").child(userId).child("lastSentWeeklyTimestamp"); userRef.setValue(ServerValue.TIMESTAMP); // [END basic_write] } }
Example 8
Source File: PersistenceTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void serverValuesArePreservedInWrite() { PersistenceManager manager = newTestPersistenceManager(); DatabaseConfig cfg = newFrozenTestConfig(); DatabaseReference ref = refWithConfig(cfg, manager); goOffline(cfg); ref.setValue(ServerValue.TIMESTAMP); waitForQueue(ref); List<UserWriteRecord> records = manager.loadUserWrites(); assertEquals(1, records.size()); UserWriteRecord record = records.get(0); assertEquals(NodeFromJSON(ServerValue.TIMESTAMP), record.getOverwrite()); }
Example 9
Source File: PersistenceTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void userOverwriteIsSaved() { PersistenceManager manager = newTestPersistenceManager(); DatabaseConfig cfg = newFrozenTestConfig(); DatabaseReference ref = refWithConfig(cfg, manager); goOffline(cfg); ref.setValue("foo-value"); waitForQueue(ref); List<UserWriteRecord> records = manager.loadUserWrites(); assertEquals(1, records.size()); UserWriteRecord record = records.get(0); assertEquals(ref.getPath(), record.getPath()); assertEquals(1, record.getWriteId()); assertEquals(NodeFromJSON("foo-value"), record.getOverwrite()); }
Example 10
Source File: DatabaseTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void updateChildrenShouldTriggerListenerWithUpdatedData() throws Exception { FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseDatabase database = FirebaseDatabase.getInstance(); auth.signOut(); Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password"); Tasks2.waitForSuccess(signInTask); DatabaseReference doc = database.getReference("restaurants").child(TestId.create()); HashMap<String, Object> originalData = new HashMap<>(); originalData.put("location", "Google NYC"); try { Task<?> setTask = doc.setValue(new HashMap<>(originalData)); Tasks2.waitForSuccess(setTask); SnapshotListener listener = new SnapshotListener(); doc.addListenerForSingleValueEvent(listener); HashMap<String, Object> updateData = new HashMap<>(); updateData.put("count", 412L); Task<?> updateTask = doc.updateChildren(new HashMap<>(updateData)); Task<DataSnapshot> snapshotTask = listener.toTask(); Tasks2.waitForSuccess(updateTask); Tasks2.waitForSuccess(snapshotTask); DataSnapshot result = snapshotTask.getResult(); HashMap<String, Object> finalData = new HashMap<>(); finalData.put("location", "Google NYC"); finalData.put("count", 412L); assertThat(result.getValue()).isEqualTo(finalData); } finally { Tasks2.waitBestEffort(doc.removeValue()); } }
Example 11
Source File: DatabaseTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void setValueShouldTriggerListenerWithNewlySetData() throws Exception { FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseDatabase database = FirebaseDatabase.getInstance(); auth.signOut(); Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password"); Tasks2.waitForSuccess(signInTask); DatabaseReference doc = database.getReference("restaurants").child(TestId.create()); SnapshotListener listener = new SnapshotListener(); doc.addListenerForSingleValueEvent(listener); HashMap<String, Object> data = new HashMap<>(); data.put("location", "Google NYC"); try { Task<?> setTask = doc.setValue(new HashMap<>(data)); Task<DataSnapshot> snapshotTask = listener.toTask(); Tasks2.waitForSuccess(setTask); Tasks2.waitForSuccess(snapshotTask); DataSnapshot result = snapshotTask.getResult(); assertThat(result.getValue()).isEqualTo(data); } finally { Tasks2.waitBestEffort(doc.removeValue()); } }
Example 12
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 13
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 14
Source File: Administrator.java From Walk-In-Clinic-Android-App with MIT License | 5 votes |
/** * Updates a service with a new name and role * @param service the service to be updated * @param name, new name for service * @param role, new role for service * @return bool if succesful * @throws IllegalArgumentException if service name exists */ public boolean updateService(DataBaseService service, String name, ServiceRole role) throws IllegalArgumentException{ if(duplicateService(name) && !service.getName().equals(name)){ throw new IllegalArgumentException("Service name already exists"); } if (service != null){ String id = service.getId(); DatabaseReference dR = FirebaseDatabase.getInstance().getReference("services").child(id); DataBaseService s = new DataBaseService(id, name, role); dR.setValue(s); return true; } return false; }
Example 15
Source File: Employee.java From Walk-In-Clinic-Android-App with MIT License | 5 votes |
public void updateWalkinClinic(){ try{ DatabaseReference dR = databaseWalkIn.child(walkInClinic.getId()); dR.setValue(walkInClinic); }catch (Exception ex){ throw new IllegalArgumentException("Clinic doesn't exist"); } }
Example 16
Source File: Employee.java From Walk-In-Clinic-Android-App with MIT License | 5 votes |
public void createWalkInClinic(WalkInClinic clinic) throws IllegalStateException{ if (walkInClinic != null){ throw new IllegalStateException("Clinic already exists"); } walkInClinic = clinic; String id_ = databaseWalkIn.push().getKey(); // get unique database key clinic.setId(id_); this.clinicId = id_; databaseWalkIn.child(id_).setValue(clinic); // save in database DatabaseReference dR = FirebaseDatabase.getInstance().getReference("users").child(getId()); DataBaseUser usr = new DataBaseUser(getId(), get_name(), get_username(), get_password(), getRole()); usr.setClinicId(id_); dR.setValue(usr); }
Example 17
Source File: SettingsFragment.java From FirebaseMessagingApp with GNU General Public License v3.0 | 4 votes |
private void saveUsername() { DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("nameAndSurname"); mDatabase.setValue(mETxtUsername.getText().toString()); }
Example 18
Source File: FirebaseHelpers.java From cannonball-android with Apache License 2.0 | 4 votes |
public static Task<Void> savePoem(Poem newPoem) { String userId = getUserId(); DatabaseReference newPoemRef = FirebaseDatabase.getInstance().getReference(userId).push(); return newPoemRef.setValue(newPoem); }
Example 19
Source File: SettingsFragment.java From FirebaseMessagingApp with GNU General Public License v3.0 | 4 votes |
private void saveStatus() { DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("status"); mDatabase.setValue(mETxtStatus.getText().toString()); }
Example 20
Source File: ItemMasterIntentService.java From stockita-point-of-sale with MIT License | 2 votes |
/** * Helper method to delete item master and all its images * @param userUid User login UID * @param itemMasterKey Item master push() key */ private void deleteOneItemMaster(final String userUid, final String itemMasterKey) { // Instantiate the server database object for itemMaster DatabaseReference locationItem = FirebaseDatabase.getInstance().getReference(); // Get to the location /encodedEmail/itemMaster + itemKey + then pass null to delete locationItem.child(userUid) .child(Constants.FIREBASE_ITEM_MASTER_LOCATION) .child(itemMasterKey).setValue(null); // Instantiate the server database object for itemImage DatabaseReference locationItemImage = FirebaseDatabase.getInstance().getReference() .child(userUid) .child(Constants.FIREBASE_ITEM_MASTER_IMAGE_LOCATION) .child(itemMasterKey); // Get the image file name then delete the images in the storage locationItemImage.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // Container ArrayList<ItemImageModel> list = new ArrayList<>(); // Iterate to pack the list with itemImageModel for (DataSnapshot snap : dataSnapshot.getChildren()) { // Instantiate the item image ItemImageModel itemImageModel = snap.getValue(ItemImageModel.class); // Pack the itemImageModel into the list list.add(itemImageModel); } // Iterate to delete each file from the storage for (ItemImageModel image : list) { // Get the imageUrl String imageName = image.getImageUrl(); // Get the file Uri Uri file = Uri.fromFile(new File(imageName)); // Initialize storage StorageReference imageStorageRef = FirebaseStorage.getInstance().getReference() .child(userUid) .child(Constants.FIREBASE_ITEM_MASTER_IMAGE_LOCATION) .child(itemMasterKey); // Delete the image from the storage imageStorageRef.child(file.getLastPathSegment()).delete(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e(TAG_LOG, databaseError.getMessage()); } }); // Get to the location /encodedEmail/itemImage + itemKey + then pass null to delete locationItemImage.setValue(null); }