when I try and create a SparseArray, like this: `...
# android
a
when I try and create a SparseArray, like this:
var array = SparseArray<ByteArray>(1)
...array ends up being empty (it shows as
“null”
in the debugger, and if I do this:
array.setValueAt(0, byteArrayOf(byte)
val value = array.get(0)
...then
value
is
null.
m
The 1 in that constructor is the initial capacity, the SparseArray is still empty. You can just add 1 item to the array without it needing to allocate more memory You need to fill it like you would a map.
a
sorry - I realised my question was incomplete - I just updated it. I try to set the first value, but the subsequent
get()
still returns
null
also
array.size()
returns zero, even after the
setValue()
m
So the
size
is
0
still since the array is empty. From documentation for setValue
Copy code
For indices outside of the range 0...size()-1, the behavior is undefined for apps targeting Build.VERSION_CODES.P and earlier, and an ArrayIndexOutOfBoundsException is thrown for apps targeting Build.VERSION_CODES.Q and later.
I'm guessing you want to use the
put
method.
a
thanks - seeing the same with
put
unfortunately
m
I've not used the class, but switching from
setValueAt
to
put
should do what you want from reading the documentation
a
is there a way I can create the
SparseArray
with it’s contents already in place?
I’ve not used this class before but I’m trying to create some mock data for a unit test
and the API I’m mocking returns
SpareArray
s unfortunately
m
Are you running this on device/emulator or as a simple JVM test? Is the code in fold
test
or
androidTest
. If running in
test
then that is because a fake version of
SparseArray
is being used and default values are returned for everything. You will have to mock the
SparseArray
also.
a
ah - this would explain a lot!
I just tried it in a Scratch and got this instead: Exception in thread “main” java.lang.RuntimeException: Stub! at android.util.SparseArray<init>(SparseArray.java:25)
thanks very much for your help @mkrussel ! 👍
g
Do not use platform version of SparseArray, use Androidx one instead, to avoid all those version specific differences and at least make it testable https://developer.android.com/reference/androidx/collection/SparseArrayCompat
But also I would just do not use SparseArray at all, until you have some very good reason except general recommendation