Android缩略图加载问题

时间:2010-03-19 12:42:05

标签: android thumbnails

我在我的项目中使用了下面提到的缩略图加载器。问题是它会正确加载所有缩略图,除了大小约为40K的缩略图。当我们的后端给出那种缩略图时,不会生成,有时这最终也会导致崩溃。

我该怎么办呢?

public class ThumbnailManager  
{

private final Map<String, Bitmap> drawableMap;
public static Context context;
private Resources res;
private int thumbnail_size;

public ThumbnailManager()
{
    drawableMap = new HashMap<String, Bitmap >();   
    res = new Resources(context.getAssets(), null, null);
    thumbnail_size = res.getInteger(R.ThumbnailManager.THUMBNAIL_SIZE);
}

public Bitmap fetchBitmap(String urlString)
{
    if(drawableMap.containsKey(urlString))
    {
        return (drawableMap.get(urlString));
    }

    //Log.d(getClass().getSimpleName(), " Image URL :: "+ urlString);
    try
    {
        InputStream is = fetch(urlString);
        android.util.Log.v("ThumbnailManager", "ThumbnailManager " + urlString);
        drawableMap.put(urlString, BitmapFactory.decodeStream(is));//Bitmap.createScaledBitmap(BitmapFactory.decodeStream(is), thumbnail_size, thumbnail_size, false));
        return drawableMap.get(urlString);
    }
    catch(Exception e)
    {
        android.util.Log.v("EXCEPTION", "EXCEPTION" + urlString);
        return null;
    }
}

public void fetchBitmapOnThread(final String urlString, final ImageView imageView)
{
    if(drawableMap.containsKey(urlString))
    {
        imageView.setImageBitmap(drawableMap.get(urlString));
        return;
    }

    if(urlString.compareTo("AUDIO") == 0)
    {
        Bitmap audioThumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.timeline_audio_thumb);
        drawableMap.put(urlString, Bitmap.createScaledBitmap(audioThumb, thumbnail_size, thumbnail_size, false));
        imageView.setImageBitmap(drawableMap.get(urlString));
        return;
    }

    final Handler handler = new Handler()
    {
        public void handleMessage(Message message)
        {
            imageView.setImageBitmap((Bitmap) message.obj);
        }
    };

    Thread thread = new Thread()
    {
        public void run()
        {
            Bitmap urlBitmap = fetchBitmap(urlString);
            Message message = handler.obtainMessage(1, urlBitmap);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

public InputStream fetch(String urlString) throws IOException, MalformedURLException
{
    final URL url = new URL(urlString);
    final URLConnection conn = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) conn;
    httpConn.setAllowUserInteraction(true);
    httpConn.setInstanceFollowRedirects(true);
    httpConn.setRequestMethod("GET");
    httpConn.connect();

    return(conn.getInputStream());
}
}

1 个答案:

答案 0 :(得分:1)

如果你在这里添加一个堆栈跟踪会很棒。但我怀疑它也是一个记忆问题。如果要将大量位图加载到内存中,它们需要的内存比原始文件大得多。防爆。你的40k缩略图可能是400k作为位图,它取决于分辨率。使用ddms并观察您的应用程序正在使用多少可用内存。如果它的工作内存少于2MB,那么BitmapFactory可能会在解码你的大拇指时产生RuntimeException。