Java Code Examples for com.google.firebase.database.DatabaseReference#addListenerForSingleValueEvent()

The following examples show how to use com.google.firebase.database.DatabaseReference#addListenerForSingleValueEvent() . 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: Helper.java    From VitonBet with MIT License 6 votes vote down vote up
public static void SetDOB(final AppCompatActivity a) {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {

            DatabaseReference db = FirebaseDatabase.getInstance().getReference()
                    .child("Users").child(user.getUid().toString()).child("dob");

            db.addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    TextView bal = (TextView)a.findViewById(R.id.dobfield);
                    bal.setText("Date of Birth: " + dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                    // ...
                }
            });
        }
    }
 
Example 2
Source File: FirebaseNotificationStore.java    From 1Rramp-Android with MIT License 6 votes vote down vote up
public static void markAsRead(String notifId) {
  String rootNode = HapRampMain.getFp();
  String username = HaprampPreferenceManager.getInstance().getCurrentSteemUsername();
  if (username.length() > 0) {
    final DatabaseReference notificationRef = FirebaseDatabase.getInstance()
      .getReference()
      .child(rootNode)
      .child(NODE_NOTIFICATIONS)
      .child(getFormattedUserName(username))
      .child(notifId);

    notificationRef.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
          notificationRef.child(NODE_IS_READ).setValue(true);
        }
      }

      @Override
      public void onCancelled(@NonNull DatabaseError databaseError) {

      }
    });
  }
}
 
Example 3
Source File: MatchesActivity.java    From TinderClone with MIT License 6 votes vote down vote up
private void getUserMatchId() {

        DatabaseReference matchDb = FirebaseDatabase.getInstance().getReference().child("Users").child(cusrrentUserID).child("connections").child("matches");
        matchDb.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    for(DataSnapshot match : dataSnapshot.getChildren()){
                        FetchMatchInformation(match.getKey());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
 
Example 4
Source File: LoadPersonRoutesAsyncTask.java    From kute with Apache License 2.0 6 votes vote down vote up
@Override
protected ArrayList<Route> doInBackground(String... params) {
    //Return the retrieved list of person's  routes from firebase
    String id=params[0];
    String route_ref="Routes/"+id;
    DatabaseReference routes_ref= FirebaseDatabase.getInstance().getReference(route_ref);
    routes_ref.keepSynced(true);
    routes_ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot routes:dataSnapshot.getChildren()){
                Route temp=routes.getValue(Route.class);
                Log.i(TAG,temp.getName());
                routes_list.add(temp);
            }
            messenger_to_activity.onTaskCompleted(routes_list);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return null;
}
 
Example 5
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void getSinglePost(final String id, final OnPostChangedListener listener) {
    DatabaseReference databaseReference = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY).child(id);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null && dataSnapshot.exists()) {
                if (isPostValid((Map<String, Object>) dataSnapshot.getValue())) {
                    Post post = dataSnapshot.getValue(Post.class);
                    post.setId(id);
                    listener.onObjectChanged(post);
                } else {
                    listener.onError(String.format(context.getString(R.string.error_general_post), id));
                }
            } else {
                listener.onError(context.getString(R.string.message_post_was_removed));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "getSinglePost(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 6
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void hasCurrentUserLikeSingleValue(String postId, String userId, final OnObjectExistListener<Like> onObjectExistListener) {
    DatabaseReference databaseReference = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.POST_LIKES_DB_KEY)
            .child(postId)
            .child(userId);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            onObjectExistListener.onDataChanged(dataSnapshot.exists());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "hasCurrentUserLikeSingleValue(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 7
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void hasCurrentUserLikeSingleValue(String postId, String userId, final OnObjectExistListener<Like> onObjectExistListener) {
    DatabaseReference databaseReference = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.POST_LIKES_DB_KEY)
            .child(postId)
            .child(userId);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            onObjectExistListener.onDataChanged(dataSnapshot.exists());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            LogUtil.logError(TAG, "hasCurrentUserLikeSingleValue(), onCancelled", new Exception(databaseError.getMessage()));
        }
    });
}
 
Example 8
Source File: Helper.java    From VitonBet with MIT License 6 votes vote down vote up
public static void SetEmail(final AppCompatActivity a) {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {

            DatabaseReference db = FirebaseDatabase.getInstance().getReference()
                    .child("Users").child(user.getUid().toString()).child("email");

            db.addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    TextView bal = (TextView)a.findViewById(R.id.emailfield);
                    bal.setText("Your Email: " + dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                    // ...
                }
            });
        }
    }
 
Example 9
Source File: DriverMapActivity.java    From UberClone with MIT License 6 votes vote down vote up
private void getAssignedCustomerInfo(){
    mCustomerInfo.setVisibility(View.VISIBLE);
    DatabaseReference mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers").child(customerId);
    mCustomerDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if(map.get("name")!=null){
                    mCustomerName.setText(map.get("name").toString());
                }
                if(map.get("phone")!=null){
                    mCustomerPhone.setText(map.get("phone").toString());
                }
                if(map.get("profileImageUrl")!=null){
                    Glide.with(getApplication()).load(map.get("profileImageUrl").toString()).into(mCustomerProfileImage);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example 10
Source File: HomeBaseFragment.java    From kute with Apache License 2.0 6 votes vote down vote up
/********************************* Data Querying Methods *************************/
//Load friends from firebase
public void getFirebaseFriend() {
    /******************** Getting Friends From Firebase *************/
    String ref = "Friends/" + getActivity().getSharedPreferences("user_credentials", 0).getString("Name", null);
    Log.d(TAG, "Firebase Reference :" + ref);
    DatabaseReference friends = FirebaseDatabase.getInstance().getReference(ref);
    friends.keepSynced(true);
    friends.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot k : dataSnapshot.getChildren()) {
                friend_list.add(k.getKey());
                Log.d(TAG, "Debug Firebase data query" + k.getValue().toString());
            }
            
            Log.d(TAG, String.format("The Friend List Size is %d",friend_list.size()));
            getFirstFriendProfile();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example 11
Source File: SignInActivity.java    From budgetto with MIT License 5 votes vote down vote up
private void updateUI(FirebaseUser currentUser) {
    if (currentUser == null) {
        progressView.setVisibility(View.GONE);
        return;
    }
    showProgressView();
    final DatabaseReference userReference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
    userReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            if (user != null) {
                startActivity(new Intent(SignInActivity.this, MainActivity.class));
                finish();
            } else {
                runTransaction(userReference);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            loginError("Firebase fetch user data failed.");
            hideProgressView();
        }
    });


}
 
Example 12
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnceFiresExactlyOnce()
    throws TestFailure, ExecutionException, TimeoutException,
        InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  final AtomicInteger called = new AtomicInteger(0);
  ref.addListenerForSingleValueEvent(
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          called.incrementAndGet();
        }

        @Override
        public void onCancelled(DatabaseError error) {
          fail("Should not be cancelled");
        }
      });

  ZombieVerifier.verifyRepoZombies(ref);

  ref.setValueAsync(42);
  ref.setValueAsync(84);
  new WriteFuture(ref, null).timedGet();
  assertEquals(1, called.get());
  ZombieVerifier.verifyRepoZombies(ref);
}
 
Example 13
Source File: DumpFeedback.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
public void dumpFeedback(final BufferedWriter writer) throws IOException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    final DatabaseReference sessionsRef = fdb.getReference("feedback/sessions");
    sessionsRef.addListenerForSingleValueEvent(new FeedbackValueEventListener(writer, latch));

    latch.await();
}
 
Example 14
Source File: HistoryActivity.java    From UberClone with MIT License 5 votes vote down vote up
private void FetchRideInformation(String rideKey) {
    DatabaseReference historyDatabase = FirebaseDatabase.getInstance().getReference().child("history").child(rideKey);
    historyDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                String rideId = dataSnapshot.getKey();
                Long timestamp = 0L;
                String distance = "";
                Double ridePrice = 0.0;

                if(dataSnapshot.child("timestamp").getValue() != null){
                    timestamp = Long.valueOf(dataSnapshot.child("timestamp").getValue().toString());
                }

                if(dataSnapshot.child("customerPaid").getValue() != null && dataSnapshot.child("driverPaidOut").getValue() == null){
                    if(dataSnapshot.child("distance").getValue() != null){
                        ridePrice = Double.valueOf(dataSnapshot.child("price").getValue().toString());
                        Balance += ridePrice;
                        mBalance.setText("Balance: " + String.valueOf(Balance) + " $");
                    }
                }


                HistoryObject obj = new HistoryObject(rideId, getDate(timestamp));
                resultsHistory.add(obj);
                mHistoryAdapter.notifyDataSetChanged();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example 15
Source File: DatabaseTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: DatabaseTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: RepoDatabase.java    From TvAppRepo with Apache License 2.0 4 votes vote down vote up
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 18
Source File: SalesPendingListFragmentUI.java    From stockita-point-of-sale with MIT License 4 votes vote down vote up
/**
 * This method will insert the current Sales Detail Pending into a local database
 * so later can be query by {@link SalesPendingCheckoutDialogFragment}
 */
private void packTheCurrentSalesDetailPendingInToLocalDatabase() {

    // Delete all data in the local database before we insert new data
    final ContentResolver contentResolver = getActivity().getContentResolver();
    contentResolver.delete(ContractData.SalesDetailPendingEntry.CONTENT_URI, null, null);

    // Get the reference to ../SalesDetailPending/...
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
            .child(mUserUid).child(Constants.FIREBASE_SALES_DETAIL_PENDING_LOCATION);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (!dataSnapshot.hasChildren()) {
                return;
            }

            // Iterate
            for (DataSnapshot snap : dataSnapshot.getChildren()) {

                // Initialize the content values
                ContentValues values = new ContentValues();

                // Initialize the model
                SalesDetailModel model = snap.getValue(SalesDetailModel.class);

                // Get the state
                String key = snap.getKey();
                String itemNumber = model.getItemNumber();
                String itemDesc = model.getItemDesc();
                String itemUnit = model.getItemUnit();
                String itemPrice = model.getItemPrice();
                String itemQty = model.getItemQuantity();
                String itemDiscount = model.getItemDiscount();
                String itemDiscountAmount = model.getItemDiscountAmout();
                String itemAmount = model.getItemAmount();

                // Pack into ContentValues object
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_PUSH_KEY, key);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_NUMBER, itemNumber);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DESC, itemDesc);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_UNIT, itemUnit);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_PRICE, itemPrice);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_QUANTITY, itemQty);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT, itemDiscount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT_AMOUNT, itemDiscountAmount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_AMOUNT, itemAmount);


                // Insert into local database
                try {
                    contentResolver.insert(ContractData.SalesDetailPendingEntry.CONTENT_URI, values);
                } catch (Exception e) {
                    Log.e(TAG_LOG, e.getMessage());
                }
            }


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e(TAG_LOG, databaseError.getMessage());
        }
    });

}
 
Example 19
Source File: GeoFire.java    From geofire-android with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the current location for a key and calls the callback with the current value.
 *
 * @param key      The key whose location to get
 * @param callback The callback that is called once the location is retrieved
 */
public void getLocation(String key, LocationCallback callback) {
    DatabaseReference keyRef = this.getDatabaseRefForKey(key);
    LocationValueEventListener valueListener = new LocationValueEventListener(callback);
    keyRef.addListenerForSingleValueEvent(valueListener);
}
 
Example 20
Source File: ItemMasterIntentService.java    From stockita-point-of-sale with MIT License 2 votes vote down vote up
/**
 * 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);

}