我使用的是基於這個question的延遲加載圖像。我正在實現一個搜索功能,當用戶輸入關鍵字時,應用程序將執行請求並使用SAX解析結果,然後將數據放入ListView中。有時圖像可以加載到ListView行的ImageView中,但有時它只會加載一個或兩個圖像,並且應用程序崩潰。延遲加載圖像有時只有作品,有時它不
下面是我的logcat輸出:
05-16 16:37:37.414: ERROR/AndroidRuntime(620): FATAL EXCEPTION: Thread-11
05-16 16:37:37.414: ERROR/AndroidRuntime(620): java.lang.NullPointerException
05-16 16:37:37.414: ERROR/AndroidRuntime(620): at com.TPLibrary.Search.ImageLoader.getBitmap(ImageLoader.java:71)
05-16 16:37:37.414: ERROR/AndroidRuntime(620): at com.TPLibrary.Search.ImageLoader.access$0(ImageLoader.java:68)
05-16 16:37:37.414: ERROR/AndroidRuntime(620): at com.TPLibrary.Search.ImageLoader$PhotosLoader.run(ImageLoader.java:173)
下面是其中錯誤是在存在的:
private Bitmap getBitmap(String url) { // line 68
//I identify images by hashcode. Not a perfect solution, but ok for the demo
String filename = String.valueOf(url.hashCode()); // line 71
File f = new File(cacheDir, filename);
//from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
//from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while(true)
{
//thread waits until there are any images to load in the queue
if (photosQueue.photosToLoad.size() == 0)
synchronized(photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized(photosQueue.photosToLoad) {
photoToLoad=photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url); // line 173
cache.put(photoToLoad.url, bmp);
Object tag = photoToLoad.imageView.getTag();
if (tag != null && ((String)tag).equals(photoToLoad.url)){
BitmapDisplayer bd =
new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity a = (Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
//allow thread to exit
}
}
}
編輯
我已經找到了那個來自PhotoToLoad
類NullPointerException
如下:
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
我該如何解決問題?
你能解釋一下嗎?我不在你指向的地方 – 2011-05-16 09:54:43
我在帖子中增加了一些解釋。我希望現在更清楚。 – Stephan 2011-05-16 09:58:03
嗯..我可以理解升技。但是,你這樣做?最後,url仍然是空的?.. – 2011-05-16 10:01:55