【发布时间】:2014-07-16 18:26:46
【问题描述】:
我希望能够使用 url 作为图像源。我找到了以下转换为位图的函数。但是,我得到一个“NetworkOnMainThreadException”。使用日志我发现
conn.connect();
,是函数崩溃的地方。
我还发现由于异常我应该使用 AsyncTask 类扩展。所以我在下面的第二段代码中使用了它。我仍然以同样的例外告终。我不完全理解错误的含义,只是我试图同时在同一个地方做太多事情。
有没有更简单的方法可以将网址转换为我可以使用的图片?如何修复我现在拥有的功能?
public static Bitmap getImageBitmap(String url) {
Log.i("bitmap","here?");
Bitmap bm = null;
Log.i("bitmap","here?");
try {
Log.i("bitmap","here?");
URL aURL = new URL(url);
Log.i("bitmap","here?");
URLConnection conn = aURL.openConnection();
Log.i("bitmap","last ?");
conn.connect();
Log.i("bitmap","here?");
InputStream is = conn.getInputStream();
Log.i("bitmap","here?");
BufferedInputStream bis = new BufferedInputStream(is);
Log.i("bitmap","here?");
bm = BitmapFactory.decodeStream(bis);
bis.close();
Log.i("bitmap","here?");
is.close();
Log.i("bitmap","here?");
} catch (IOException e) {
Log.e("img", "Error getting bitmap", e);
}
return bm;
}
使用异步任务:
class taskRunner extends AsyncTask<String, URL, Bitmap>{
public static Bitmap getImageBitmap(String url) {
Log.i("bitmap","here?");
Bitmap bm = null;
Log.i("bitmap","here?");
try {
Log.i("bitmap","here?");
URL aURL = new URL(url);
Log.i("bitmap","here?");
URLConnection conn = aURL.openConnection();
Log.i("bitmap","last ?");
conn.connect();
Log.i("bitmap","here?");
InputStream is = conn.getInputStream();
Log.i("bitmap","here?");
BufferedInputStream bis = new BufferedInputStream(is);
Log.i("bitmap","here?");
bm = BitmapFactory.decodeStream(bis);
bis.close();
Log.i("bitmap","here?");
is.close();
Log.i("bitmap","here?");
} catch (IOException e) {
Log.e("img", "Error getting bitmap", e);
}
return bm;
}
非常感谢您抽出宝贵时间阅读本文。
【问题讨论】:
-
这不是重复的 - 发帖人知道这个问题,但即使 在 参考该答案后解决它也有问题。但是当前问题的问题是没有堆栈跟踪来显示当前发生异常的哪里 - 找到它将是修复它的关键。