1

尝试下载 jpg 文件时出现 nullPointerException。它是在 AsyncTask 方法中完成的,我无法在调试器中跟踪程序流,可能是因为它是异步的。我的跟踪显示在它停止之前读取了 2 条记录。我使用端口 8000 作为我的本地服务器,它停止的 url 是

      http://10.0.2.2:8000/my_album/5_irises.jpg".   

下载 jpeg 和 png 文件有什么特别之处,还是我的 url 编码不正确?url中的下划线有问题吗?另外,每次下载后我必须关闭连接吗?

 begin of loop {
  ........
   new AccessImages().execute(urlstring);
  }  ......end of loop 

 private class AccessImages extends AsyncTask<String, Void, Bitmap> {
        protected Bitmap doInBackground(String... urladds){
            return downloadImage(urladds[0]);
        }
        protected void onPostExecute(Bitmap bm) {
            bitmap_photo[itemcount] = bm;
            itemcount++;
        }
        }

  private Bitmap downloadImage(String url) {
        Log.d("downloadImage", url);
        Bitmap bmap = null;
        InputStream inStream = null;
    //  Drawable drawable = null;
        try {
            inStream = openHttpConnection(url);
            Log.d("inStream", String.valueOf(inStream));
        //  drawable = Drawable.createFromStream(inStream, "src");
            Log.d("before bmap", url);
            bmap = BitmapFactory.decodeStream(inStream);
            Log.d("after bmap", url);
            inStream.close();

        }
        catch (IOException el) {
            el.printStackTrace();
        }
        return bmap;
    }

    private InputStream openHttpConnection(String urlString) throws IOException {

        InputStream inStream = null;
        int checkConn = -1;
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        try {

            Log.d("try openhttpconnection", urlString);
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            checkConn = httpConn.getResponseCode();
            if (checkConn == HttpURLConnection.HTTP_OK) {
                inStream = httpConn.getInputStream();
                Log.d("instream", urlString);

            }

        }
        catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return inStream;
    }

我刚刚发现 NullPointerException 在这条指令中:

   inStream.close();  

什么会导致这种情况?

好的。现在我纠正了 inStream 不为空,但现在我从以下指令中得到 NullPointerException:bitmap_photo[itemcount] = bm;

  if(bm != null)
            {
            bitmap_photo[itemcount] = bm;
            itemcount++;
            }

我不能检查位图中的空值还是数组有问题?我应该补充一点,我按如下方式创建了 bitmap_photo 数组:这是一个问题吗?

          Bitmap [] bitmap_photo;
4

0 回答 0