2017-09-17 66 views
-1

我已經在Stack Overflow和Internet上研究瞭如何從URL加載圖像並將其作爲Bitmap(原本一個.png文件)。我按照說明進行操作,代碼如下,代碼的類別爲AsyncTask無法從HttpUrlConnection(PNG到位圖)加載圖像,inputStream中的位圖爲空

try { 
    imageUrl = new URL(currentApp.getImageURL()); 
    HttpURLConnection urlConnection = (HttpURLConnection) 
    imageUrl.openConnection(); 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.setDoInput(true); 

    ***urlConnection.connect(); 
    InputStream inputStream = urlConnection.getInputStream(); 
    imageBitmap = BitmapFactory.decodeStream(inputStream); 
    viewHolder.tvImage.setImageBitmap(imageBitmap); 
    inputStream.close();*** 

    } catch (MalformedURLException e) { 
     Log.d(TAG, "getView: " + e.toString()); 
    } catch (IOException e) { 
     Log.d(TAG, "getView: " + e.toString()); 
    } finally { 

} 

爲我所用的調試工具來幫助我,我發現,從連接響應代碼是200,但imageBitmap = BitmapFactory.decodeStream(inputStream);,我得到imageBitmap空值。

預先感謝您!

+0

看到logcat的,什麼是崩潰的原因。 – 2017-09-17 05:09:10

+0

你是否在任何線程中運行代碼? – 2017-09-17 05:10:41

+0

什麼是你的logcart消息? – 2017-09-17 05:16:06

回答

0

Decode Stream return null如果輸入流爲空或不能用於解碼位圖。嘗試從另一個URL下載圖像,我下載的YouTube播放列表的縮略圖和其工作110%爲我好,試試這個代碼

public class DownloadImagesTask extends AsyncTask<ImageView, Void, ImageView> { 
    ImageView iv=null; 
    Bitmap bitmap=null; 
    String url=null; 

    public DownloadImagesTask(ImageView iv,int position,String url) { 
     this.iv = iv; 
     this.position=position; 
     this.url = url; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

    } 

    @Override 
    protected ImageView doInBackground(ImageView... url) { 
     try { 
       Log.e("url", this.url); 
       URL ulrn = new URL(this.url); 
       HttpURLConnection con = (HttpURLConnection) ulrn.openConnection(); 
       InputStream is = con.getInputStream(); 
       this.bitmap = BitmapFactory.decodeStream(is); 
       if (null != this.bitmap) 
       { 
        return iv; 
       } 
     }catch(Exception e){} 
     return null; 
    } 




    @Override 
    protected void onPostExecute(ImageView result) { 
     if(result!=null) { 
      this.iv.setImageBitmap(bitmap); 

     } 
     else 
      iv.setImageResource(R.drawable.loading); 
    } 


} 
+0

謝謝你的回答,但我試過了,位圖仍然是空的 – justinj

+0

你試過用另一個鏈接嗎?可能是鏈接被破壞? –

+0

感謝您的幫助,但我沒有嘗試過幾個鏈接,都沒有工作 – justinj