I am creating chat application so want generate unique message id . Is it possible never create duplicate message id.
-
better use mongoDB._id can create a id for you. – Rushi Ayyappa Nov 17 '16 at 11:19
-
Possible duplicate of [Android SMS setting unique ID](http://stackoverflow.com/questions/11377730/android-sms-setting-unique-id) – mabe02 Nov 17 '16 at 11:42
5 Answers
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")

- 8,440
- 5
- 49
- 69
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

- 1,255
- 1
- 19
- 20
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!

- 2,707
- 3
- 28
- 58
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.

- 18
- 6
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());

- 237,138
- 77
- 654
- 440