Reputation: 5469
I have been playing around with Bundle.putStringArrayList
ArrayList<String> myArrayList = new ArrayList<String>();
ArrayList<String> keys = new ArrayList<String>();
Bundle name_bundle = new Bundle();
for (int i = 0; 10 > i; i++){
myArrayList.add(i + " first");
myArrayList.add(i + " second");
keys.add(i + " key");
name_bundle.putStringArrayList(keys.get(i), myArrayList);
myArrayList.clear();
}
I would expect the output (when debugging) to be (after running the loop a couple of times, but not to completion):
Bundle[{2 key=[2 first, 2 second], 1 key=[1 first, 1 second], 0 key=[0 first, 0 second]}]
However, it is:
Bundle[{2 key=[2 first, 2 second], 1 key=[2 first, 2 second], 0 key=[2 first, 2 second]}]
Is this a bug, or is this how it is intended to work? And if so, is it because it is reusing the same array?
Since the key is different ever time, I am not sure why it would over write every value.
Especially since this:
ArrayList<String> keys = new ArrayList<String>();
Bundle name_bundle = new Bundle();
for (int i = 0; 10 > i; i++){
keys.add(i + " key");
String s = i + " string";
name_bundle.putString(keys.get(i), s);
}
Produces this (after running the loop a couple of times):
Bundle[{2 key=2 string, 1 key=1 string, 3 key=3 string, 0 key=0 string}]
EDITED
When using the following:
ArrayList<String> one = new ArrayList<String>();
ArrayList<String> two = new ArrayList<String>();
ArrayList<String> tmpkey = new ArrayList<String>();
one.add("1 first array");
one.add("2 first array");
two.add("1 second array");
two.add("2 second array");
tmpkey.add("first key");
tmpkey.add("second key");
name_bundle.putStringArrayList(tmpkey.get(0), one);
name_bundle.putStringArrayList(tmpkey.get(1), two);
You get:
Bundle[{first key=[1 first array, 2 first array], second key=[1 second array, 2 second array]}]
The fact that it requires new arraylists kind of defeats the purpose of being able to reuse an arraylist by using .clear(), however.
Just to verify, when adding the following to the end of the above:
one.clear();
one.add("will it work?");
name_bundle.putStringArrayList(tmpkey.get(2), one);
You get:
Bundle[{third key=[will it work?], first key=[will it work?], second key=[1 second array, 2 second array]}]
Is anyone aware of a work-around wherein I can reuse the arraylist so I can use it in a loop? Or perhaps a different approach all together? The reason I went for a loop is because I didn't know how many times I would have to reuse the arraylist, or since it doesn't allow you to, how many arraylists I would need.
Upvotes: 0
Views: 1910
Reputation: 17077
You are calling #clear()
on your myArrayList
& reusing it - causing all keys to reference the same list (until/if they are parceled I guess). Try allocating a new ArrayList
for each call to #putStringArrayList(...)
.
Upvotes: 1