Is there something wrong if i use
Long uniqueId = System.currentTimeMillis()/1000;
String documentName = ""+ uniqueId;
as for example a document name?
Unless the user has a wrong Date it will be always unique right?
Or is there a better way to create always unique number values?
The reason i use Long uniqueId = System.currentTimeMillis()/1000;
is because it has to be unique even if the user generates that document from another device without the same data which means that i cannot create and save unique values and simply add +1 to it.
If you use
System.currentTimeMillis()/1000
then if you save 2 files in the same second you will have 2 identical names for 2 different files.
So i suggest you to use
UUID.randomUUID().toString()
Related
I am trying to pass unique value to notificationManager.notify(). The shortest way that's coming into my mind is System.currentTimeMillis().
So i did following to get unique value.
Long getCurrentTime= System.currentTimeMillis();
int id= Math.abs(getCurrentTime.intValue());
notificationManager.notify("com.myapp.app",id , notification);
System.currentTimeMillis() returns 13 digit long value.
I am little afraid about the length of this generated id.
I want to know that what is recommanded length of id in notificationManager.notify() method.
Why don't you just create a static counter in your main activity and you increment it before call notify
Main Activity
public static int NOTIFY_COUNTER_ID= 1;
Notification class
notificationManager.notify("com.myapp.app",++MainActivity.NOTIFY_COUNTER_ID, notification);
EDIT
As you mentioned in the comment, the app might be killed so you won't be able to access the static resource.
In order to avoid that you can use Shared preferences to save your incremental ID.
Or IMHO if you use Math.rand() with a big "gap" you should be fine.
System.currentTimeMillis() is too long to manage identifier.
Id is int, its 32 bit in java,
Recommended value will be -2,147,483,648 to +2,147,483,647
I am developing a cross platform game for which I needs to generate unique identifier (User ID) for each user. I known some platform (Android or iOS) specific approaches to get device related identifiers but I am looking for a solution independent of the device identifiers.
User ID Requirements:
Independent of the device's platform
Offline implementation (no communication with any servers)
Without sign-up process
I have implemented one approach to create User IDs where I store the system time when the game was launched for the first time on the device.
I have following questions:
Are there any other approaches to generate User IDs (which will meet the above requirements)?
What are the common approaches to create unique identifiers with taking any information from the user?
Are there any third party plug-ins to implement User IDs?
I would appreciate any suggestions and thoughts on this topic.
EDIT:
There are lot of responses to use UUID/GUID. Generally, this approach looks fine but I am looking for a solution which can generate same User ID even if the user reinstall the game.
Have you looked at UUID from Java?
https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html
EDIT: The following links might help using UUID for unique identifiers.
Best practices for permissions & Identifiers
Instance ID
When you say user id, are you talking about a public id such as an username, or a database id?
If you are talking about a database id, go for a GUID/UUID. T-sql for example have the NEWID() method that will return a GUID that doesn't exist in the database yet. I am sure that whichever database you go for you will find some way to use a GUID.
https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql
As per my opinion your System current time is the best method for generating Unique User Id.
For Android :
System.currentTimeMillis() returns you the unique 13 digit number which can be used as User Id.
But When you get current time in iOS then it is 10 digit number which generates. So you can multiply it by 1000 to make User Id platform Independent.
Happy Coding...
Assuming that your usernames are unique, you could simply takje the md5 hash of your usernames to get an unique ID (string). e.g. in php:
$userID = md5($username);
because m5 hash functions exist in nearly every programming language you should be able to use this ID on all possible plattforms.
And if you arer looking for a numeric ID, you even can calculate a qunique number from md5.
See represent md5-hash as an integer - stack question for more details
Just generate a long string of random characters. For example, generates a 10 long string of alphanumerics ...
private String GetId(){
String[] chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
StringBuilder s = new StringBuilder(10);
for(int i = 0;i<10;i++){
int pos = (int) (Math.random() * 62);
String c = "";
if (pos > chars.length-1){
pos = pos - chars.length;
c = chars[pos].toUpperCase();
}else{
c = chars[pos];
}
s.append(c);
}
return s.toString();
}
I am doing an application where I need to store some numbers and when someone call on phone I need to check if incoming number is present in my database or not.
What I did
I stored phone numbers in shared preferences. Internally android uses Map for this purpose.
Problem:
Lets say I stored 9089889899 (10 digit phone number). Now if I get an incoming call from this number it may BroadcastReceiver having 09089889899 or +91-9089889899 number for the same.
So my problem is that if I stored a number into preferences then how can I match the incoming number is present in preferences or not.
I suggest that you use something like libphonenumber to handle the phone numbers independent of the format.
There is also some functions for formatting and comparing numbers in PhoneNumberUtils.
SharedPreferences settings;
settings = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//for get sharepref
String phone = settings.getString("9089889899", 0);
//strPhone = has your broadcast receive number
if(strPhone.contains(phone)){
}else{
}
If you are using the mobile phone as key for the sharedpreference you can:
retrive all the values of your sharedpreference: see here
iterate through the key set : see here
for every key use the contains String method: see here
Edit: why are you not use a content provider?
You can try out the following code in your BroadCast Receiver.
here "abc" with the name of your Shared Perefence. Assuming that num here is the number you got from the Broadcast Receiver:
In the code, the last 10 digits are taken out and compared, as these are what stored in SharedPreference.
SharedPreferences sp = getSharedPreferences("abc",Context.MODE_PRIVATE);
HashMap< String, String>hMap = (HashMap<String, String>) sp.getAll();
String num = "+91-9089889899";
if( hMap.containsValue(num.substring(num.length()-10))){
System.out.println("number present");
}
here is the regex that will match all the phone formats
(((([0-9]){0,1})(([0-9]){10}))|([0-9]){10}|(\+([0-9]){1,2}([0-9]{10})))
first part matches 0 - 1231231234
second part matches 1231231234
last part +91 - 1231231234
update
actually this is much better
(((([0-9]){0,1})(([0-9]){10}))|(\+([0-9]){1,2}([0-9]{10})))
I'm using the following code to fill up a ContentValues variable.
public ContentValues getContentValues() {
ContentValues initialValues = new ContentValues();
initialValues.put("blt_name", m_name);
initialValues.put("blt_pictureURI", m_pictureURI);
initialValues.put("blt_description", m_description);
initialValues.put("blt_UUID", getUUID().toString());
return initialValues;
}
My problem is that put() is putting the UUID and the name in the same hash location! I have no idea why. When creating the initialValues variable it creates an internal hashmap having 7 slots. When putting the values, key is added in slot 0, name is ALSO added in slot 0 (overwriting uuid), pic is added in slot 3 and desc is added in slot 7.
All four keys are, of course, different values, declared as final Strings.
I tried new ContentValues(4) in order to force them into the right spot, that was worse. 2 values were overwritten.
[Edit] I just tried changing the order of the puts. By moving the UUID so that it is put() last, it still overwrites slot 0 in hashmap. (I know what you are thinking, and YES the keys are unique.)
[EDIT] I tried it with the following code, and it works perfectly. I'm at a lost. I also edited the original question because I tried it with hard coded strings, and that didn't work either.
initialValues.put("a", m_name);
initialValues.put("b", m_pictureURI);
initialValues.put("c", m_description);
initialValues.put("d", getUUID().toString());
Any help would be appreciated,
-I_Artist
Are you sure that this is a problem? ContentValues is essentially a hash table, not an array. It's almost inevitable that there will be collisions between different keys. But collisions do not mean that you've lost your data. The only real way to be sure that your data is (or is not) stored appropriately is to try to get the data from the ContentValues object:
String newName = initialValues.get("blt_name");
String newPicture = initialValues.get("blt_pictureURI");
String newDesc = initialValues.get("blt_description");
String newUUID = initialValues.get("blt_UUID");
// now do something with these values to check if they're right...
I bet you'll find that the data have their correct values. If not, there's more going on than the code that you've posted can show us.
What happens if you hard code your keys as "Key1", "Key2", "Key3", "Key4"? I know you said that you are sure your keys are unique, however I am still curious if there could be something we are all not seeing.. Maybe you could show us an example of the values being set for the keys and their values?
(Ha! First time using stackoverflow, obviously this is not an answer...)
(So this might actually be your answer)
The HashMap computes an index into that array using the hashCode() of the key. It doesn't just use the hashCode() modulo the array size, but rather uses a more complex function of the hashCode().
It may be possible that the keys: "blt_UUID" AND "blt_name" are being hashed to the same value. This being the case, the two keys are being given the same index and a "collision" is occurring and the value is being overwritten. Try changing the key to something else, maybe using all capitalization, and try it again.
Best of luck.
I have a question. In my app I have saved in my database some lists. Each list has asociated a date in this format 6-June-2011. How can I order these lists by date? I wrote I function like that :
public Cursor getAll(){
return (mDb.rawQuery("SELECT _id, Title, Shop , Data , Budget_allocated ," +
" Budget_spent FROM Lists ORDER BY Data",null));
}
but it doesn't work fine. I think it compare only the day. For example, if I have 31-May-2011 and 6-June-2011, it will say that the first date is after the second date.
It is possible what I am trying to do? Should I modify the date in format like this :6-06-2011?
Thanks..
I don't know anything about android development, but it sounds like your date field is stored as a string rather than a date, is that correct?
If so, you can either:
Change your table so that field is a date (then it should compare correctly)
Or store it in a standard format such that the default string comparison sorts dates correctly. Since string comparison sorts first on first character, second on second character, etc, this would be putting the biggest time difference first, ie. "2011-05-31" (include the zeroes).
(You should be able to convert the field by making a new field, copying the data from the old field into the new field in the correct format, and then deleting the old field and renaming the new one, or more simply if you simply want to change the format of the text. You should be able to do this either from code, or with an "update" query, AFAIK.)
Use a date format as follows...yyyy-MM-dd HH:mm:ss. This is guaranteed to be sortable in ascending or descending order.
If your Data column is not of type datetime there may be an issue. Take a look at this related SO question and answers:
SQL ORDER BY date problem