Вопрос

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.

Другие советы

Have you though about UUID hashcode + System.currentTimeMillis(), hashcode can duplicate but it has 32bit size, so it hardly possible. If you add System.currentTimeMillis() you will minimize chance for sameId.

If you need one record per device, than you can use UUID, but... take into account that UUID can be sometimes null, and also you need to add additional permissions to get it. In this case most reliable will be: System.currentTimeMillis() + Random.nextLong().

It depends on records number, if you want to have 10 000 - 100 000 unique records than choose one method above and you will be ok. If you are looking for something much bigger than check UUID, Imei, Sim serial number.

This is a nice androidId, unique for device, but beware, it can be null sometimes, thats why I adviced to use System.currentTimeMillis(). import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

Why not try a combination(even simple append ) of UUID and System.currentTimeMillis()? That will always be unique(provided UUID is not null)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top