0

我正在遍历游标并填充包含来自游标的信息包的SparseArraywith ArrayList

// An ArrayList to hold all of our components per section
ArrayList<ObjectKanjiLookupChar> al = new ArrayList<ObjectKanjiLookupChar>();
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();

do
{
    // Read values from the cursor
    int id = cursor.getInt(cursor.getColumnIndex("_id"));
    String component = cursor.getString(cursor.getColumnIndex("component"));
    int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));

    // Create a new object for this component so we can display it in the GridView via an adapter
    ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
    oklc.setCharacterID(id);
    oklc.setCharacter(component);
    oklc.setStrokeCount(compStrokes);

    al.add(oklc);

    // Add headers whenever we change stroke groups
    if(compStrokes != strokesSection)
    {
        compArray.put(strokesSection, al);
        al.clear();
        strokesSection = compStrokes;
    }
}
while(cursor.moveToNext());

// Add the final group of components to the array
compArray.put(strokesSection, al);

紧接着,我遍历SparseArray

for(int i = 0; i < compArray.size(); i++)
{
    Integer strokes = compArray.keyAt(i);
    ArrayList<ObjectKanjiLookupChar> alComp = compArray.get(strokes);

    // DEBUG
    Log.i("DialogKanjiLookup", "Components in Section " + strokes + ": " + alComp.size());

    ll.addView(createNewSection(String.valueOf(strokes), alComp));
}

由于某些未知原因,Log()上面的调用报告了alComp条目。我验证了当我进入.ArrayList.size()时返回大于 0 的数字,所以在遍历. 到底是怎么回事?put()SparseArraySparseArray

4

1 回答 1

2

我怀疑问题来自这段代码:

 if(compStrokes != strokesSection)
    {
        compArray.put(strokesSection, al);
        al.clear(); // Here
        strokesSection = compStrokes;
    }

添加到 SparseArray 后,您清除了数组列表。您可能会认为,在将列表添加到 SparseArray 之后,SparseArray 会保留 ArrayList 的副本。但是,它们实际上共享相同的引用。由于您清除了 ArrayList,因此您也清除了 SparseArray 中的那个。

下面的代码应该可以解决这个问题。

// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();

do
{
    // Read values from the cursor
    int id = cursor.getInt(cursor.getColumnIndex("_id"));
    String component = cursor.getString(cursor.getColumnIndex("component"));
    int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));

    // Create a new object for this component so we can display it in the GridView via an adapter
    ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
    oklc.setCharacterID(id);
    oklc.setCharacter(component);
    oklc.setStrokeCount(compStrokes);

    ArrayList<ObjectKanjiLookupChar> al = compArray.get(comStrokes);
    if(al == null) {
        al = new ArrayList<ObjectKanjiLookupChar>();
        compArray.put(comStrokes, al);
    }

    al.add(oklc);
}
while(cursor.moveToNext());
于 2013-09-12T01:44:25.703 回答