gpt4 book ai didi

java - 这个 NullPointerException 的来源是什么

转载 作者:行者123 更新时间:2023-12-01 13:18:37 25 4
gpt4 key购买 nike

好的,我正在编写一个 Android 应用程序,并尝试下载 Bitmap 并将其设置为 ImageView。相关部分的代码如下:

    private class GetContactInfo extends AsyncTask<String, Void, ContactInfo[]> {

@Override
protected ContactInfo[] doInBackground(String... url) {
// Instantiate what is needed
URL json = null;

//Set the JSON URL
try {
json = new URL(url[0]);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

// Use Jackson library to read out the data from the contacts page
try {
contacts = mapper.readValue(json, ContactInfo[].class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

//Add everything into the bitmap ArrayList
for (int i = 0; i < contacts.length; i++) {
String imageURL = contacts[i].getSmallImageURL();

// Download the Bitmap and add it to the ArrayList
try {
bitmap.add(downloadBitmap(imageURL));
} catch (IOException e) {
e.printStackTrace();
}
}

// Return statement
return contacts;
}
<小时/>
public Bitmap downloadBitmap(String imageURL) throws IOException {

URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
if (bitmap == null) {
Log.e("Null", "Bitmap null");
}

return bitmap;
}

日志永远不会捕获位图为空,或者至少不会显示它(我在堆栈跟踪中看到还有 4 个错误,但它们从未显示出来,而且我不知道如何扩展它显示其他错误。)

NullPointerException 出现在 bitmap.add(downloadBitmap(imageURL));线。所以不知何故我的downloadBitmap函数返回空结果。有什么想法吗?

编辑:我不确定这是否重要,但 URL 中的图像是 .jpeg 文件。

编辑2:将其放在评论中,以便我也将其编辑到我的帖子中,位图被声明为全局变量,如下所示ArrayList<Bitmap> bitmap;这样我以后就可以在 onPostExecute 方法中使用它。

最佳答案

正如你所说,错误发生在行

bitmap.add(downloadBitmap(imageURL)); 

这意味着罪魁祸首是您的位图变量,而不是 downloadBitmap(imageURL) 方法。

此外,在您的编辑中,您提到您已将位图声明为全局变量 - ArrayList 位图;

为了访问(向其中添加位图对象)这个全局声明的变量,您必须对其进行初始化。

在你的 onCreate 中做 -

bitmap = new ArrayList<Bitmap>(); 

NPE 必须下台。

关于java - 这个 NullPointerException 的来源是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com