将jpg图像下载到android时无效的url

时间:2013-03-14 22:23:21

标签: android asynchronous bitmap download

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

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

下载jpegs与png文件有什么特别之处或者我的网址编码错误吗?下划线是网址中的问题吗?另外,每次下载后我是否必须关闭连接?

 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不为null但现在我从以下指令得到NullPointerException:bitmap_photo [itemcount] = bm;

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

我不能检查位图中的空值或者数组是否有问题?我应该补充一点,我创建了bitmap_photo数组,如下所示:这是一个问题吗?

          Bitmap [] bitmap_photo;

0 个答案:

没有答案