In an application I’m currently working on I have my first activity with a ListView which is populated from an ArrayList saved to the apps internal memory. Either by using the menu button to select ‘Add’ or by tapping an existing item in the menu I can get to my second activity which is an edit page.
In the first activity if the Add button is pressed, there are no extras passed in the intent and no fields (text boxes, etc) need to be filled in the edit activity. If an existing item is clicked in the first activity, this passes the row ID of that item as an extra in the Intent, with the key string as “_id”.
I understand that *Bundle.getLong(“_id”);* should return null if no extra has been passed with the intent. My problem is that for some reason, getLong() is always returning 0. I tried putting some gibberish as the key string for getLong() but it still returns 0. Has anyone come across this problem before?
I would also like to add that I have two other sets of activities similar to this, using the same method to get the rowId if it has been passed, and they all work fine.
I haven’t been able to find any common problems that might cause this. Thanks in advance for any help.
[EDIT]
Apologies for any confusing and not showing this code previously. As a few people have commented getLong will return 0 if it cant find anything, however the code I use sets mRowId to null if this is the case, or at least I assume it does. This bit kinda confused my but it seemed to work when no other extra was passed with the intent.
mRowId = extras != null
? extras.getLong("_id")
: null;
I also had another mess around and found that if any extra value is passed with the intent (regardless of its key) it will cause it to return 0 rather than null. I assume this code doesn’t work if another extra is passed. If that is the case is there a better way to pass the rowId if necessary and set it as null if nothing is passed.
Actually the docs say that if the mapping is not found “0L” is returned.
http://developer.android.com/reference/android/os/Bundle.html#getLong(java.lang.String)
(also the type “long” is a primitive and cannot be null).
You could use this:
http://developer.android.com/reference/android/os/Bundle.html#getLong(java.lang.String,%20long)
in which you can define a default value to receive when the key is not found (e.g. -1).