10

I'm using a list of unique int ids against a list of user names as a fast lookup table and decided to use the sparseArray but I would like to be able print to log the entire list from time to time for debugging purposes.

The SparseArray is not iterable and isn't much like the util.Map interface

user245357
  • 131
  • 1
  • 7
  • Similar question (with answers) can be found [here](http://stackoverflow.com/questions/7999211/iterate-through-sparsearray/8006994#8006994) – Wasky Jul 05 '12 at 14:34

3 Answers3

16

Mice was correct, code would look something like this;

for(int i = 0; i < sparseArray.size(); i++){
    int key = sparseArray.keyAt(i);
    Object value = sparseArray.valueAt(i);
}
Pork 'n' Bunny
  • 6,740
  • 5
  • 25
  • 32
  • 1
    More explanation on this solution in the comments here: http://stackoverflow.com/a/8006994/579234 – Sogger Oct 05 '12 at 18:41
4

Use SparseArray.size() to get total size.

Use SparseArray.keyAt and valueAt to get key/value in given index.

Pointer Null
  • 39,597
  • 13
  • 90
  • 111
  • 2
    Example with some more explanation for this solution here: http://stackoverflow.com/a/8006994/579234 – Sogger Oct 05 '12 at 18:42
0

Here's how to display a SparseArray content for debug traces.

public static String sparseArrayToString(SparseArray<?> sparseArray) {
    StringBuilder result = new StringBuilder();
    if (sparseArray == null) {
        return "null";
    }

    result.append('{');
    for (int i = 0; i < sparseArray.size(); i++) {
        result.append(sparseArray.keyAt(i));
        result.append(" => ");
        if (sparseArray.valueAt(i) == null) {
            result.append("null");
        } else {
            result.append(sparseArray.valueAt(i).toString());
        }
        if(i < sparseArray.size() - 1) {
            result.append(", ");
        }
    }
    result.append('}');
    return result.toString();
}
Kevin Gaudin
  • 9,927
  • 3
  • 32
  • 34