你知道为什么我在调用 getInputStream() 函数时会捕获 NullPointerException 吗?
我记录了 URLConnection 的日志,链接是正确的...我不知道问题出在哪里。
public Bitmap getBitmap(String resolution) {
URL url = null;
Bitmap bmp = null;
switch(resolution) {
case "thumb":
url = thumbUrl;
break;
case "low":
url = lowresUrl;
break;
case "standard":
url = standardresUrl;
break;
}
try {
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
}
catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bmp;
}
最佳答案
鉴于您发布的代码,唯一合理的结论是 conn
为 null
。您可以使用 conditional operator ? :
检查这一点。 (三元)如
// InputStream in = conn.getInputStream();
InputStream in = (conn != null) ? conn.getInputStream() : null;
或者类似的东西
InputStream in = null;
if (conn != null) {
in = conn.getInputStream();
}
我还注意到您的 switch
没有 default:
,因此 url
也可能是 null
(但如果是这种情况,您会在 openConnection()
上得到一个 Exception
)。
关于java - getInputstream 上的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28246475/