2016-12-12 144 views
1

我試圖通過使用Volley庫將圖像下載到ImageView中。
我將Volley庫的響應注入到ImageView中,但我沒有得到期望的結果。如何使用Volley下載圖像?

請檢查我的代碼並建議我可以進行更改以獲得所需結果。

public class MainActivity extends AppCompatActivity { 
    Button response_click; 
    TextView text_response; 
    RequestQueue requestQueue; 
    ImageView image_download; 
    String server_url="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Starburst_in_NGC_4449_(captured_by_the_Hubble_Space_Telescope).jpg/1024px-Starburst_in_NGC_4449_(captured_by_the_Hubble_Space_Telescope).jpg"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     response_click=(Button) findViewById(R.id.click_response); 
     text_response=(TextView) findViewById(R.id.text_response); 
     image_download=(ImageView)findViewById(R.id.image_download); 
    } 
    public void response_click(View view){ 
     requestQueue= Volley.newRequestQueue(getApplicationContext()); 
     StringRequest stringRequest=new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 
       image_download.setImageResource(Integer.parseInt(response)); 


      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       text_response.setText("ou got an error..."); 
      } 
     }); 

    } 
} 

回答

4

您正在使用錯誤類型的請求。有一個ImageRequest

請參閱本文檔:Volley: Request an Image

ImageView mImageView; 
String url = "http://i.imgur.com/7spzG.png"; 
mImageView = (ImageView) findViewById(R.id.myImage); 
... 

// Retrieves an image specified by the URL, displays it in the UI. 
ImageRequest request = new ImageRequest(url, 
    new Response.Listener<Bitmap>() { 
     @Override 
     public void onResponse(Bitmap bitmap) { 
      mImageView.setImageBitmap(bitmap); 
     } 
    }, 0, 0, null, 
    new Response.ErrorListener() { 
     public void onErrorResponse(VolleyError error) { 
      mImageView.setImageResource(R.drawable.image_load_error); 
     } 
    }); 
// Access the RequestQueue through your singleton class. 
MySingleton.getInstance(this).addToRequestQueue(request); 

或者你可以使用NetworkImageView,也亂射的一部分。

但是,請注意,谷歌已經棄用淘汰阿帕奇自己的排球,但有一個臨時解決辦法:How to use the legacy Apache HTTP client on Android Marshmallow?

最喜歡的人會建議,如果可以的話,請更新到畢加索http://square.github.io/picasso/