簡體   English   中英

此NullPointerException的來源是什么

[英]What's the source of this NullPointerException

好的,所以我正在編寫一個Android應用程序,並試圖下載位圖並將其設置為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;
}

日志從不捕獲位圖為null,或者至少不顯示位圖(我在堆棧跟蹤中看到還有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必須走了。

從Internet下載圖像時,應使用異步請求。 downloadBitmap該連接正在另一個線程中進行下載,但是無論是否完成下載,主線程都會立即返回bitmap

您在哪里初始化bitmap 據我所知,它為null,並且您正在使用該null對象,因此出現了Null Pointer Exception。 那是從您提供的信息中得出的。 如果錯誤發生在函數內部,則是另一回事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM