2013-06-29 4 views
0

URL에서 사진을 다운로드하여 Android의 ImageView에 표시하려면이 코드가 필요합니다.Android에서 여러 URL의 이미지를 여러 개의 다른 ImageView로 다운로드하여 표시합니다.

ArrayList 또는 여러 URL의 배열을 다운로드하여 다른 ImageViews에 표시 한 경우이를 루프하는 방법을 잘 모르겠습니다. 진행 방법에 대한 도움이나 통찰력에 감사드립니다! 고맙습니다!

public class DisplayPhotoTask extends AsyncTask<String, Void, Bitmap> { 
    @Override 
    protected Bitmap doInBackground(String... urls) { 
     Bitmap map = null; 
     for (String url : urls) { 
      map = downloadImage(url); 
     } 
     return map;  
    } 

    //sets bitmap returned by doInBackground 
    @Override 
    protected void onPostExecute(Bitmap result) { 
     ImageView imageView1 = (ImageView) findViewById(R.id.imageView); 
     imageView1.setImageBitmap(result); 
    } 

    //creates Bitmap from InputStream and returns it 
    private Bitmap downloadImage(String url) { 
     Bitmap bitmap = null; 
     InputStream stream = null; 
     BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
     bmOptions.inSampleSize = 1; 

     try { 
      stream = getHttpConnection(url); 
      bitmap = BitmapFactory.decodeStream(stream, null, bmOptions); 
      stream.close(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     return bitmap; 
    } 

    //makes httpurlconnection and returns inputstream 
    private InputStream getHttpConnection(String urlString) throws IOException { 
     InputStream stream = null; 
     URL url = new URL(urlString); 
     URLConnection connection = url.openConnection(); 

     try { 
      HttpURLConnection httpConnection = (HttpURLConnection) connection; 
      httpConnection.setRequestMethod("GET"); 
      httpConnection.connect(); 

      if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
       stream = httpConnection.getInputStream(); 
      } 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     return stream; 
    } 

} 

답변

1

당신은 예를 들어 정말 쉽게 가지고,이

protected Bitmap doInBackground(String... urls) { 
    List<Bitmap> bitmaps = new ArrayList<Bitmap>; 
    for (String url : urls) { 
     bitmaps.add(downloadImage(url)); 
    } 
    return bitmaps;  
} 

protected void onPostExecute(List<Bitmap> result) { 
    //... 
} 

같은 목록 개미 쓰기 무언가로 AsyncTask를 결과를 만들하지만 난 정말 당신을 추천 할 것입니다 구글에 의해 작성 발리 라이브러리를 사용하는 것입니다 수 있습니다 강력한 API (여기에는 Google I/O 세션 인 https://developers.google.com/live/shows/474338138 및 저장소 https://android.googlesource.com/platform/frameworks/volley/)

관련 문제