【发布时间】:2017-04-27 09:00:14
【问题描述】:
我正在尝试制作一个从 http 连接中获取图像的简单函数。它以前可以工作,现在它会抛出一些错误。我没有对代码进行任何更改。输入流也不为空。它正在返回预期的数据。
D/skia: ---- read threw an exception
D/skia: --- SkAndroidCodec::NewFromStream returned null
I/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
这是我在异步任务中的参考代码:
@Override
protected Bitmap doInBackground(String... url){
try {
InputStream in = openHttpConnection(url[0]);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
return bitmap;
} catch (IOException e) {
Log.i("ERROR", e.toString());
return null;
}
}
private static InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
httpConn.disconnect();
} catch (Exception e) {
Log.i("ERROR", e.toString());
throw new IOException("Error connecting");
}
return in;
}
【问题讨论】:
-
它之前工作过然后恢复更改......我赌
httpConn.disconnect();在你开始阅读输入流之前 -
Null 对象是我无法访问的代码中的静态类。为清楚起见,输入流不会返回 null。
-
之前已经说过
httpConn.disconnect();。删除它。它以前从来没有工作过。
标签: java android bitmap urlconnection