Strange ArrayAdapter behaviour
I'm writing an application for Android-based tablets. While I have come very far in development, there is one bug I don't understand and can't get rid of. I have a GridView with a custom ArrayAdapter, which contains some downloadable items in it. Each item in this grid is a clickable relative layout, which looks something like this:
<RelativeLayout>
<FrameLayout />
<TextView />
<TextView />
<ProgressBar />
</RelativeLayout>
When an item is clicked, the app will try to find it on sd-card and show it. If it fails, then it will start downloading it in it's own thread. File-downloading method is very standard, except for two th开发者_Go百科ings things - it has, as said, it's own thread and it updates progress-bar after downloading each data-chunk (which, at this moment, is 2048 bytes):
while ((n = in.read(b,0,chunkSize)) >= 0) {
out.write(b,0,n);
if (handler != null && progressbar != null) {
/* Update progressbar:*/
currentBytes += n;
final int nbytes = currentBytes;
handler.post(new Runnable() {
public void run() {
progressbar.setProgress(nbytes);
}
});
}
}
This works perfectly well. Here's how it looks like in the real world (after clicking on 3rd icon; these items are just placeholders, but the downloaded files are real):
[I couldn't post an image (not enough rep), so here's a link]
http://i52.tinypic.com/20zb8jq.png
In the same time I can start a second download and it will still work perfectly. I can also add elements at the end and it will work too. There is a slight problem, however. Whenever I use a search button, which starts a new activity, and go back to this activity, same gridview will look like this:
[I couldn't post an image and only one hyperlink (not enough rep), so here's a link with a space]
http:// i54.tinypic.com/16kqgxg.png
It's still downloading the right element, it just shows the wrong progressbar. The magazine will still be shown after downloading completes. Another unwanted effect is that ALL items, even those downloading and with progress bars, are set to be clickable (I disable it before starting downloading). Here is the code (a bit shortened, but it doesn't matter) updating the adapter:
List<Magazine> newList = cm.getMyMags(); // Returns a list of current magazines
List<Magazine> oldList = cachedAdapter.mags; // I use List.toArray() method in getView in Adapter.
for (Magazine mag : newList) {
if (!oldList.contains(mag)) {
cachedAdapter.add(mag);
}
}
I know it's not the most efficient way to do this, but right now all I care about is making it work.
I tried to update the list itself and call notifyDataSetChanged(), but it gave exactly the same results. Does anyone know what might cause this problem?Thank you for your time.
精彩评论