Can firebase generate an unique ID as we wish? - java

Like firebase generating uid. Can firebase generate an unique ID as we wish? If it is possible? how to write a code for it in the following order?
For example PRO00013, PRO00014, PRO00015....
I am asking here, because I'm working in a project for online shopping. when a user adds a product to their inventory it needs to assign an id for every product. that is must be in the human readable format. If it is not possible, just tell me no, I can accept that answer.

You can just call .push() to get randomUUID and then ref.child(randomUUID).setValue(object)
where the object can contain field ID such as PRO00013.
If this doesn't fit your needs you can just place ref.child("PRO00013").setValue(object) and not include field id in this object.
Now you want to get id PRO00014 for the next pushed object. This ain't gonna happen with firebase.
But you can get the last ID added in this ref with query on
ref.orderByKey().limitToLast(1);
Now you have the last added object from this node and you can simply get the key which will be PRO00013.
1. Cast it to String
2. Remove "PRO" from this string
3. Cast the remaining to integer
4. Add 1 to this integer
5. Create new string variable and give it value "PRO" + the new integer
6. Now push the object in ref.(the new string variable).setValue(object).
Now I don't know if you gonna implement this logic in a cloud function accepting some sort of params but if this is the case - this should work just fine.
I also want to know WHY xD

Related

Cannot use HashMap for TIMESTAMP in child

I am trying a new timestamp, and want to insert it as a child. How to do that?
I have read this post:
Write serverValue.timestamp as child in Firebase .. and still don't understand
I've tried to enter ServerValue.TIMESTAMP into child and unsuccessful.
This my code:
Object timestamp = ServerValue.TIMESTAMP;
reference.child(String.valueOf(timestamp)).child(uid).child("Status").setValue(cA);
I've read this:
How to save the current date/time when I add new value to Firebase Realtime Database
I follow the code in it, and not work properly -->
What should I do?
The ServerValue.TIMESTAMP can only be written into a value, it cannot be used as the key in the database. So if you want to store the timestamp, you will have to write it as the value of a property. If you want to have chronologically ordered, unique keys, use the push() method.
So combined:
reference.push().setValue(ServerValue.TIMESTAMP);

Create Unique Message Id Like whats app

I am creating chat application so want generate unique message id .
Is it possible never create duplicate message id.
MongoDB's ObjectId is pretty complex is probably one of the good randomness from a unique id point of view.
So you can take a sneak peek in their source code to see how they generate it.
Leaving the definition from their official documentation here for posterity:
ObjectIds are small, likely unique, fast to generate, and ordered.
ObjectId values consists of 12-bytes, where the first four bytes are a
timestamp that reflect the ObjectId’s creation, specifically:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
Example of Mongo's ObjectId:
ObjectId("507f1f77bcf86cd799439011")
There could be many ways to generate one! One common way would be to generate timestamp value and use it as a id which is also unique.
For example you can do this:
public int createID(){
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
return id; }
you can also try and make it string and add any specific string format with it to make it more unique according to ur apps need!
base on your poor description, you can create compound id. for example you can create your ides with user id+timestamp. and if you use this pattern, your user id length must be same for all ides. so if it is not, you have to add "0" befor your current id to obtain equal length for all of your user ides
for better description:
String uniquemsgid= userid+ System.currentTimeMillis();
as a matter of fact, your user have a unique id an timestamp is unique for this user.
caution: if you use only timestamp or a date with any format, this method cant guarantee a unique message id. because two user can create a message at a moment
You can make a Random randomId= new Random();
int id = randLan.nextInt(99999) + 1;
Then you check if Id is already given, and if yes, try again, if not, you have an Id.
if(randomId == someOtherId), do same process again.
You might want to use device IMEI number for this, which is always unique and quite easy to get.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Add above permission in your manifest file and then use the below two lines to get the IMEI.
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
long id = Long.parseLong(mngr.getDeviceId());

What kind of Java List should I use to maintain a set of data

I have a dataset, and I'm not sure which type of List or Map to use in Java.
Following is a sample dataset.
There are 2 columns, Users and Errors.
A user can be repeated. Errors are random and there won't be any duplicates.
Users Errors
User A Error 1
User B Error 2
User A Error 3
User C Error 4
and I should be able to use the list to get all errors per user at the end.
I tried a hashmap, but it only retrieves the last entry for user.
Thanks in advance.
You can use a HashMap<User,List<Error> (not sure if there are User and Error classes or if they are represented by Strings or some numeric type, but you get the idea).
This will make it easy to obtain the List of all errors for a given user.
You can use Map of String to List.
Depending on java version you might need to do manual checks if given key exists (in such case add the error) or doesn't (create list and add a single error)

how can i generate a item code value with auto increment integer plus an identification integer

i'm creating a Itemcode for my inventory system i want the number system of integer values like this using java
for example this
for group 1 the code would be 001 -
0010001,
0010002
for group 2 the code would be 002-
0020003,
0020004
for group 3 the code would be 003-
0030005,
0030006
the items are encoded individually so when i add a new entry it will detect which group it belongs to and generate it desired item code the first 3 digits will be the corresponding Value identification in which group it belongs to the the next 4 digit code will just be the increment value..and would be stored as one integer using MySQL database
You need to decide:
Are the item codes to be represented as: one integer, a pair of integers (group & item), a string ... or something else.
Is the numbering scheme per the first example or the second one. (You seem to have chosen one scheme now ...)
How you are going to populate the items and codes. Do you read the codes? Do you generate them all in one go while loading items from a file. Do you create items and item ids one at a time (e.g. interactively).
How is this information going to be "stored"? In memory only? In a flat file? In a database? (MySQL ... ?)
These decisions will largely dictate how you implement the item id "generation".
Basically, your problem here is that >>you<< need to figure out what the requirements are. Once you have done that, the set of possible solutions will reduce to a manageable size, and you can then either work it out for yourself or ask a sensible question.

User Defined Index for an ArrayList of IDs

I'm in a situation where (in Java) I need to define an arraylist of generated ids. I don't know how many would be generated at any given time, but I do know that when one is generated, the user who generated it would need to set a custom index, and be able to retrieve it by that index. What would be the generally accepted standard way of storing and working with a data structure like this? An arraylist of arrays?
Sounds like a use case for a Map which you can use the ID as the key and a value (or potentially an array of values, if multiple values can have the same id) as the value. You can then index into the map and retrieve data using the key. The benefit is that this works even if you want to change the ID from an int to a String or even some other idea.
The problem with using a List like this is if I have two ids 1 and 3000 then there are 2998 indices that are wasted, which is not exactly ideal.

Categories