How to convert Instant to Int

2.2k Views Asked by At

In my app I have AlarmManager to set Scheduled notification.

In order to have unique notification to each Item, I need to set unique id to each pending intent, otherwise the notification run over each other.

my problem is that my PK is string, not an int. my closest thing to Int in my Item model is Instant, which represent the time that the notification should send, and It's unique.

And because PendingIntent id is only an int, how can I convert Instant to Int? Or should I take another approach and create data field in my model just to hold the pending intent ID?

In my understanding I shoudn't convert it directly cause it will mess with the date/time and potentially(?) won't by unique

2

There are 2 best solutions below

0
Marc H. On

Simple String to int conversion could made with hashCode. But a hash code is by definition not unique. If possible then changing the type from int to String is probably the best option. If you really need a conversion I would recommend you create something like and IndexProvider.

public interface IndexProvider {

    /**
     * Idempotent index provider for id conversion.
     * Be aware of memory consumption because the implementations are allowed to cache id's.
     * @param id unique id
     * @return a cached unique id or a new unique id
     */
    int getIndex(String id);

}

This would allow you to simple solve the problem. You could use a map in the implementation for holding the String id's . Other idea would be to solve this problem in the database. For example a new table which holds you an int id for every String id. At the end you will have to modify something and you will have Pro's and Contra's for every approach.

This is probably not a full answer but I have not enough reputation for commenting.

0
telibay On

That should work I think:

instant.get(ChronoField.INSTANT_SECONDS)