com.google.firebase.database.ServerValue Java Examples

The following examples show how to use com.google.firebase.database.ServerValue. 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: FeedsActivity.java    From friendlypix-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onPostLike(final String postKey) {
    final String userKey = FirebaseUtil.getCurrentUserId();
    final DatabaseReference postLikesRef = FirebaseUtil.getLikesRef();
    postLikesRef.child(postKey).child(userKey).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                // User already liked this post, so we toggle like off.
                postLikesRef.child(postKey).child(userKey).removeValue();
            } else {
                postLikesRef.child(postKey).child(userKey).setValue(ServerValue.TIMESTAMP);
            }
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {

        }
    });
}
 
Example #2
Source File: Message.java    From chat21-android-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
public Map asFirebaseMap() {
    Map map = new HashMap();
    map.put("sender",null);
    map.put("sender_fullname",senderFullname);
    map.put("recipient",null);
    map.put("recipient_fullname",recipientFullname);
    map.put("text",text);
    map.put("status",null);
    map.put("timestamp", ServerValue.TIMESTAMP);
    map.put("type",type);
    map.put("channel_type",channelType);
    map.put("metadata",metadata);
    map.put("attributes",attributes);

    return map;

}
 
Example #3
Source File: FirebaseOpsHelper.java    From CourierApplication with Mozilla Public License 2.0 6 votes vote down vote up
private void sendNewOrderToDbWithTimestampAndPhone() {
    final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
    dbRef.child("users").child(getCurrentUserUid()).addListenerForSingleValueEvent(
            new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()) {
                mNewOrder.setPhoneNumber(String.valueOf(dataSnapshot.child("phone").getValue()));
                mNewOrder.setTimeStamp(ServerValue.TIMESTAMP);
                sendNewOrderToDb(dbRef);
            } else {

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

        }
    });
}
 
Example #4
Source File: ChatActivity.java    From ChatApp with Apache License 2.0 6 votes vote down vote up
@Override
protected void onPause()
{
    super.onPause();

    running = false;

    FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId).child("online").setValue(ServerValue.TIMESTAMP);

    if(messagesList.size() > 0 && messageEditText.getText().length() > 0)
    {
        FirebaseDatabase.getInstance().getReference().child("Chat").child(currentUserId).child(otherUserId).child("typing").setValue(0);
    }

    removeListeners();
}
 
Example #5
Source File: ReferralActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void rewardUser(AuthCredential credential) {
    // [START ddl_referral_reward_user]
    FirebaseAuth.getInstance().getCurrentUser()
            .linkWithCredential(credential)
            .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    // Complete any post sign-up tasks here.

                    // Trigger the sign-up reward function by creating the
                    // "last_signin_at" field. (If this is a value you want to track,
                    // you would also update this field in the success listeners of
                    // your Firebase Authentication signIn calls.)
                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    DatabaseReference userRecord =
                            FirebaseDatabase.getInstance().getReference()
                                    .child("users")
                                    .child(user.getUid());
                    userRecord.child("last_signin_at").setValue(ServerValue.TIMESTAMP);
                }
            });
    // [END ddl_referral_reward_user]
}
 
Example #6
Source File: UserInfo.java    From AvI with MIT License 6 votes vote down vote up
@Exclude
@Override
public Map<String, Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();
    result.put("lastModifiedTime", ServerValue.TIMESTAMP);
    result.put("authId", authId);
    result.put("name", name);
    result.put("email", email);
    result.put("pictureUrl", pictureUrl);
    result.put("employment", employment);
    result.put("education", education);
    result.put("knowledgeableIn", knowledgeableIn);
    result.put("interests", interests);
    result.put("currentGoals", currentGoals);
    result.put("locationLat", locationLat);
    result.put("locationLon", locationLon);

    return result;
}
 
Example #7
Source File: ChatMessage.java    From AvI with MIT License 5 votes vote down vote up
@Exclude
@Override
public Map<String, Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();
    result.put("sender", senderId);
    result.put("message", message);
    result.put("timestamp", ServerValue.TIMESTAMP);
    return result;
}
 
Example #8
Source File: ElectricityMonitorActivity.java    From android-things-electricity-monitor with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_electricity_monitor);

    firebaseDatabase = FirebaseDatabase.getInstance().getReference();
    final String key = firebaseDatabase.child(FIREBASE_LOGS).push().getKey();

    electricityLog = new ElectricityLog();

    final DatabaseReference onlineRef = firebaseDatabase.child(FIREBASE_INFO_CONNECTED);
    final DatabaseReference currentUserRef = firebaseDatabase.child(FIREBASE_ONLINE_ENDPOINT);
    onlineRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {
            Log.d(TAG, "DataSnapshot:" + dataSnapshot);
            if (dataSnapshot.getValue(Boolean.class)) {
                electricityLog.setTimestampOn(ServerValue.TIMESTAMP);
                final DatabaseReference currentLogDbRef = firebaseDatabase.child(FIREBASE_LOGS).child(key);
                currentLogDbRef.setValue(electricityLog);

                currentUserRef.setValue(true);
                currentUserRef.onDisconnect().setValue(false);

                electricityLog.setTimestampOff(ServerValue.TIMESTAMP);
                currentLogDbRef.onDisconnect().setValue(electricityLog);

            }
        }

        @Override
        public void onCancelled(final DatabaseError databaseError) {
            Log.d(TAG, "DatabaseError:" + databaseError);
        }
    });
}
 
Example #9
Source File: OfflineActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: EntityTranslator.java    From Android-MVP-vs-MVVM-Samples with Apache License 2.0 5 votes vote down vote up
@Exclude
public static Map<String, Object> toMap(final CheckIn checkIn) {

    final Map<String, Object> result = new HashMap<>();

    result.put("email", checkIn.email);
    result.put("checkInMessage", checkIn.checkInMessage);
    result.put("timestamp", checkIn.timestamp == null ? ServerValue.TIMESTAMP : checkIn.timestamp);

    return result;
}
 
Example #11
Source File: PersistenceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: DoorbellActivity.java    From doorbell with Apache License 2.0 5 votes vote down vote up
/**
 * Upload image data to Firebase as a doorbell event.
 */
private void onPictureTaken(final byte[] imageBytes) {
    if (imageBytes != null) {
        final DatabaseReference log = mDatabase.getReference("logs").push();
        final StorageReference imageRef = mStorage.getReference().child(log.getKey());

        // upload image to storage
        UploadTask task = imageRef.putBytes(imageBytes);
        task.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                // mark image in the database
                Log.i(TAG, "Image upload successful");
                log.child("timestamp").setValue(ServerValue.TIMESTAMP);
                log.child("image").setValue(downloadUrl.toString());
                // process image annotations
                annotateImage(log, imageBytes);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // clean up this entry
                Log.w(TAG, "Unable to upload image to Firebase");
                log.removeValue();
            }
        });
    }
}
 
Example #13
Source File: BaseActivity.java    From stockita-point-of-sale with MIT License 5 votes vote down vote up
/**
 * This helper method is to check and listen for the user connection, and also
 * log time stamp when the user disconnect.
 */
private void presenceFunction() {

    // Initialize the .info/connected
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    mUserPresenceRef = database.getReference(".info/connected");

    // Get an instance reference to the location of the user's /usersLog/<uid>/lastOnline
    final DatabaseReference lastOnlineRef = database.getReference()
            .child(Constants.FIREBASE_USER_LOG_LOCATION)
            .child(mUserUid)
            .child(Constants.FIREBASE_PROPERTY_LAST_ONLINE);


    // Initialize the listeners
    mUserPresenceListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            // Get the boolean value of the connection status
            boolean connected = dataSnapshot.getValue(Boolean.class);

            if (connected) {

                // when I disconnect, update the last time I was seen online
                lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            // Nothing
        }
    };

    // Add the listeners instance to the database database instance
    mUserPresenceRef.addValueEventListener(mUserPresenceListener);

}
 
Example #14
Source File: Utility.java    From stockita-point-of-sale with MIT License 5 votes vote down vote up
/**
 * 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 #15
Source File: MyEmailer.java    From quickstart-java with Apache License 2.0 5 votes vote down vote up
public static void sendNotificationEmail(String email, String uid, String postId) {
    // TODO(developer): send email to user notifying them that one of their posts got a new star
    System.out.println("sendNotificationEmail: MOCK IMPLEMENTATION");
    System.out.println("sendNotificationEmail: " + email);

    // Save the date of the last notification sent
    // [START write_fan_out]
    Map<String,Object> update = new HashMap<String,Object>();
    update.put("/posts/" + postId + "/lastNotificationTimestamp", ServerValue.TIMESTAMP);
    update.put("/user-posts/" + uid + "/" + postId + "/lastNotificationTimestamp", ServerValue.TIMESTAMP);

    FirebaseDatabase.getInstance().getReference().updateChildren(update);
    // [END write_fan_out]
}
 
Example #16
Source File: MyEmailer.java    From quickstart-java with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: FirestackModule.java    From react-native-firestack with MIT License 5 votes vote down vote up
@ReactMethod
public void serverValue(@Nullable final Callback onComplete) {
  WritableMap timestampMap = Arguments.createMap();
  for (Map.Entry<String, String> entry : ServerValue.TIMESTAMP.entrySet()) {
    timestampMap.putString(entry.getKey(), entry.getValue());
  }

  WritableMap map = Arguments.createMap();
  map.putMap("TIMESTAMP", timestampMap);
  onComplete.invoke(null, map);
}
 
Example #18
Source File: ChatAuthentication.java    From chat21-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public void updateNodeContacts(String appId, String userId, String email, String name, String surname) {
        Log.d(DEBUG_LOGIN, "updateNodeContacts: userId == " + userId + ", email == "
                + email + ", name == " + name + ", surname == " + surname);

        // retrieve node contacts
        DatabaseReference mNodeContacts = FirebaseDatabase.getInstance().getReference()
                .child("apps/" + appId + "/contacts/" + userId);

//            // add uid
//            mNodeContacts
//                    .child("uid")
//                    .setValue(userId);

        // add email
        mNodeContacts
                .child("email")
                .setValue(email);

        // add name
        mNodeContacts
                .child("name")
                .setValue(name);

        // add surname
        mNodeContacts
                .child("surname")
                .setValue(surname);

        // add timestamp
        mNodeContacts
                .child("timestamp")
                .setValue(ServerValue.TIMESTAMP);
    }
 
Example #19
Source File: Participant.java    From justaline-android with Apache License 2.0 5 votes vote down vote up
public Participant(Boolean anchorResolved, Boolean isPairing) {
    this.readyToSetAnchor = false;
    this.anchorResolved = anchorResolved;
    this.isPairing = isPairing;
    this.lastSeen = new HashMap<>();
    lastSeen.put("timestamp", ServerValue.TIMESTAMP);
}
 
Example #20
Source File: PersistenceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void ackForServerValueYieldsResolvedValueInCache() throws Throwable {
  PersistenceManager manager = newTestPersistenceManager();
  DatabaseConfig cfg = newFrozenTestConfig();
  DatabaseReference ref = refWithConfig(cfg, manager);
  QuerySpec query = QuerySpec.defaultQueryAtPath(ref.getPath());

  new WriteFuture(ref, ServerValue.TIMESTAMP).timedGet();

  Node node = manager.serverCache(query).getNode();
  long drift = System.currentTimeMillis() - (Long) node.getValue();
  assertThat(Math.abs(drift), lessThan(2000l));
}
 
Example #21
Source File: PersistenceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void persistedServerValuesAreResolved() throws Throwable {
  PersistenceManager manager = newTestPersistenceManager();
  manager.saveUserOverwrite(new Path("foo"), NodeFromJSON(ServerValue.TIMESTAMP), 1);
  DatabaseConfig cfg = newFrozenTestConfig();
  DatabaseReference ref = refWithConfig(cfg, manager).getRoot().child("foo");
  List<EventRecord> records = ReadFuture.untilCount(ref, 2).timedGet();
  // There will be two events, one local and one when the server responds
  long now = System.currentTimeMillis();
  long drift1 = (Long) records.get(0).getSnapshot().getValue() - now;
  long drift2 = (Long) records.get(1).getSnapshot().getValue() - now;
  assertThat(Math.abs(drift1), lessThan(2000l));
  assertThat(Math.abs(drift2), lessThan(2000l));
}
 
Example #22
Source File: Capabilities.java    From ChatApp with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: ProfileActivity.java    From ChatApp with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPause()
{
    super.onPause();

    FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId).child("online").setValue(ServerValue.TIMESTAMP);
}
 
Example #24
Source File: UsersActivity.java    From ChatApp with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPause()
{
    super.onPause();

    FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("online").setValue(ServerValue.TIMESTAMP);
}
 
Example #25
Source File: MyPresenceHandler.java    From chat21-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public void dispose() {
    if (myPresenceListeners != null && myPresenceListeners.size() > 0) {
        myPresenceListeners.clear();
        Log.d(DEBUG_MY_PRESENCE, "MyPresenceHandler.disconnect:" +
                " myPresenceListeners has been cleared.");
    }

    // when the device disconnects, remove the deviceId connection from the connections list
    if (connectionsRef != null && StringUtils.isValid(deviceId)) {
        connectionsRef.child(deviceId).removeValue();
        Log.d(DEBUG_MY_PRESENCE, "MyPresenceHandler.disconnect: " +
                "connectionsRef with deviceId: " + deviceId + " has been detached.");
    }

    // when the user is disconnect, update the last time he was seen online
    if (lastOnlineRef != null) {
        lastOnlineRef.setValue(ServerValue.TIMESTAMP);
        Log.d(DEBUG_MY_PRESENCE, "MyPresenceHandler.disconnect:" +
                " lastOnlineRef has been updated");
    }

    // detach all listeners
    if (connectedRef != null && valueEventListener != null) {
        connectedRef.removeEventListener(valueEventListener);
        valueEventListener = null;
        Log.d(DEBUG_MY_PRESENCE, "MyPresenceHandler.disconnect: " +
                "connectedRef valueEventListener has been detached");
    }
}
 
Example #26
Source File: MainActivity.java    From ChatApp with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPause()
{
    super.onPause();

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

    if(currentUser != null)
    {
        FirebaseDatabase.getInstance().getReference().child("Users").child(currentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
    }
}
 
Example #27
Source File: ChatGroup.java    From chat21-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public java.util.Map<String, String> getCreatedOn() {
    return ServerValue.TIMESTAMP;
}
 
Example #28
Source File: Conversation.java    From chat21-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public java.util.Map<String, String> getTimestamp() {
    return ServerValue.TIMESTAMP;
}
 
Example #29
Source File: LogEntry.java    From firebase-appengine-backend with Apache License 2.0 4 votes vote down vote up
public Map<String, String> getTime() {
  return ServerValue.TIMESTAMP;
}
 
Example #30
Source File: Message.java    From firebase-appengine-backend with Apache License 2.0 4 votes vote down vote up
public Map<String, String> getTime() {
  return ServerValue.TIMESTAMP;
}