You can simply perform a push()
function. What that would do is create a random id for your node.
databaseRef.push(); // You have created a node with a random id.
However, if you want to create a node with a numeric id you can have a function that creates a numeric value:
public static long generateRandom(int length) {
Random random = new Random();
char[] digits = new char[length];
digits[0] = (char) (random.nextInt(9) + '1');
for (int i = 1; i < length; i++) {
digits[i] = (char) (random.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
The function is from: 12 Digit unique random number generation in Java
You pass a length and it creates a random numeric value. The ideal length for you would be 5. Then you could go and do this:
long randomFiveDigitValue = generateRandom(5);
databaseRef.child(String.valueOf(randomFiveDigitValue)).setValue(your_object);
Another option would be to use an integer hash-code. It would decrease hash collisions, but you should be ready to handle them as with the previous function too. You could take an identifier from the order, like the date or even a mixture of factors, and do this:
//Replace all these variables with the respective value
String factors = "your_date" + "user_uid" + "product_name";
factors.hashCode(); //String date returns a integer hash value.
Here are the hashCode()
collisions for 50000
randomly generated products:
COLLISIONS BETWEEN: 2 Items
ITEM 1: DATE: 24-5-2019 08:09 PM + NAME: IPHONE + UID: 4J3IF93KSKK0295[L3
ITEM 2: DATE: 24-5-2019 09:08 PM + NAME: MARKER + UID: 534KKJI903[PCO4OP5
It took a long time to generate these and I think collisions are really rare now. Like 1 to 50000 ratio
. My algorithm could have been flawed, but still this way the collisions are really low.