1

I created a chat app where I store the messages in firestore.

For each message, I'm giving a random document ID prior to storing it.

In order to give a random ID, I used the accepted solution as it was described in this answer - link

I do as follows in my code:

RandomString gen = new RandomString( 40, ThreadLocalRandom.current() );
String randomString = gen.nextString();

Map<String, Object> newComment = new HashMap<>();
-----ADDING SOME VALUES to newComment----
collectionReference.document( randomString ).set( newComment );

What I have noticed is that sometimes it generates the same ID.

How I tested it? I ran my application on the emulator and added a message. Then, I rebuilt the app and ran it again on the emulator and it generated the same ID.

I'm not sure if it happened only to the emulator when I build the app or not but is there a way to make sure that the values won't repeat? (I'm not talking about the small probability that it will happen, I'm talking about the case that when I go back to the previous layout it happens after single random).

Thank you

Ben
  • 1,737
  • 2
  • 30
  • 61
  • By the way, for a unique identifier you can use the standard [*universally unique identifier (UUID)*](https://en.wikipedia.org/wiki/Universally_unique_identifier). See [`UUID`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/UUID.html) class. A UUID is a 128-bit value canonically represented textually using a 36-character hexadecimal string grouped with hyphens. – Basil Bourque May 24 '21 at 15:58

0 Answers0