My app stores offline data in sqlite and then sync it to online server on user choice. I need a unique id for each row in the sqlite so that when i sync / update i can manage status and other things for each row.
The Unique id should be unique across all devices using my app. The option i tried System.currentTimeMillis() but it seems it can be duplicate across devices. The other options i searched were UUID or merging 2 values like System.currentTimeMillis() and Random.nextLong() to create unique value
What is the best and reliable approach for doing this ?
You were right on with your UUID. UUID means Universally Unique IDentifier, and it's specifically designed for this distributed computing environment you have, with multiple devices generating unique records. As such, it is "practically unique." This means exactly what it says -- in practice, it will be unique across all your devices and across time. Most implementations employ some form of device ID (such as the practically unique MAC address), as well as a time-element and encrypted location information (geo-IP or similar).
In Java/Android, you can use UUID.randomUUID().toString()
to generate unique primary keys for your SQLite database. Once you sync back to the server, those primary keys will practically be unique.
I would recommend against attempting to implement your own UUID scheme (based on AndroidID, MAC address, IMEI, System Time, etc). While you might gain slight storage advantages, the effort in development and troubleshooting, IMHO, is just not worth it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With