2014-05-19 2 views
0

내 listview의 각 요소에는 텍스트와 이미지가 포함되어 있습니다. JSON을 사용하여 url에서 텍스트를 가져 와서 listview에 표시 할 수 있습니다. 이미지의 URL을 가져올 수도 있지만 목록에 표시 할 수는 없습니다. 여기 내 코드입니다 :JSON을 사용하여 listview에서 URL의 이미지를로드 할 수 없습니다.

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    lv = (ListView) findViewById(R.id.newslist); 
    img_url = (TextView) findViewById(R.id.iamge_url); 
    contactList = new ArrayList<HashMap<String, Object>>(); 

    new GetContacts().execute(); 
} 

private class GetContacts extends AsyncTask<Void, Void, Void> { 
protected Void doInBackground(Void... arg0) { 
     // Creating service handler class instance 
     ServiceHandler sh = new ServiceHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       contacts = jsonObj.getJSONArray(TAG_POSTS); 




       // looping through All Contacts 
       for (int i = 0; i < contacts.length(); i++) { 
        // JSONObject c = contacts.getJSONObject(i); 


        JSONObject posts = contacts.getJSONObject(i); 

        JSONArray attachment = posts.getJSONArray("attachments"); 
        for (int j = 0; j< attachment.length(); j++){ 
        JSONObject obj = attachment.getJSONObject(j); 
        JSONObject image = obj.getJSONObject("images"); 

        JSONObject image_small = image.getJSONObject("tie-small"); 

        String imgurl = image_small.getString("url"); 
        Bitmap picture = getBitmapFromURL(imgurl); 

        HashMap<String, Object> contact = new HashMap<String, Object>(); 
        contact.put("image_url", imgurl); //this image i want to load 
        contact.put("icon", picture);  //this displays fine 
        contact.put(TAG_TITLE, title);  // this displays fine 
        contactList.add(contact); 
        }  

       } 

protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 


     ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.third_row, 
       new String[] {"image_url",TAG_TITLE,"icon"}, 
new int[] {R.id.iamge_url,R.id.headline3,R.id.imageicon}); 

     lv.setAdapter(adapter); 


    } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 

     return null; 
    } 

이것은 URL에서 이미지에 geting 내 방법 getBitmapFromURL()이다 :

public static Bitmap getBitmapFromURL(String src) { 
    try { 
     Log.e("src",src); 
     URL url = new URL(src); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     Bitmap myBitmap = BitmapFactory.decodeStream(input); 
     Log.e("Bitmap","returned"); 
     return myBitmap; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Log.e("Exception",e.getMessage()); 
     return null; 
    } 
} 

에 오류가 없습니다. 응용 프로그램도 충돌하지 않지만 목록보기에서는 이미지가 표시되지 않습니다. 내가 말한 logcat에 오류가 발생한다 :

unable to decode stream java.io.filenotfoundexception /android.graphics.bitmap (no such file or directory) 

나는 url을 점검했다. 그것은 효과가있다. URL을 사용하여 브라우저에서 이미지를 볼 수 있습니다. 문제가 어디 있는지 알 수 없습니다.

+0

이미지를 표시하고 싶다면 headImageViewHelper 또는 UniversalImageLoader와 같은 라이브러리를 사용하십시오. 여기에서는로드하려는 이미지의보기 및 URL을 전달해야합니다. (당신은 또한 이미지를 가져 오는 경우에 대비하여 3 번째 매개 변수로 기본 드로어 블을 제공 할 수 있습니다.) – Kaustuv

+0

글쎄 .. 이클립스가 자바 힙 에러를 제공하기 시작하면서 라이브러리를 사용하는 것이 싫지만 .. 시도해 볼 것입니다. –

답변

0

먼저 JSON에서 imageUrl을 가져 와서이 메서드를 사용하여 비트 맵으로 변환하십시오.

public static Bitmap getBitmap(String imageUrl) 
{ 
    if (imageUrl != null && !imageUrl.equals("null")) 
    { 
     Bitmap bmp = null; 
     try 
     { 
      URL url = new URL(imageUrl); 
      bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
     } catch (MalformedURLException mue) 
     { 
      Log.e("Get Thumbnail", "Error retrieving thumbnail"); 
      mue.printStackTrace(); 
     } catch (IOException io) 
     { 
      Log.e("Get Thumbnail", "Error retrieving thumbnail"); 
      io.printStackTrace(); 
     } 
     return bmp; 
    } 
    return null; 
} 

사용이가 크기를 조정하여 목록보기 어댑터의 getView()에서 다음

public static Bitmap getResizedBitmap(Bitmap image) 
{ 
    return Bitmap.createScaledBitmap(image, 175, 175, true); 
} 

과을 (당신은 또한 확장하고 크기를 조정하려면 이미지 뷰의 XML 속성을 사용할 수 있지만)

// Scale and set the Image 
    if (myArrayList.get(position).getImage() == null) 
    { 
    // set default image if there is no image 
     imgThumbnail.setImageResource(R.drawable.placeholder); 
    } else { 
     imgThumbnail.setImageBitmap(myArrayList.get(position).getImage()); 
    } 
+0

getview() 메소드가 없습니다. 난 그냥 간단한 어댑터를 사용하여. SimpleAdapter()를 사용하여 이미지를 어떻게 두어야합니까? –

0

json right에서 URL을 받고 있습니다 ... 해당 URL을 사용하여 ur 이미지를로드 할 수 있습니다 ...

AndroidMenifest.xml

<!-- Internet Permissions --> 
    <uses-permission android:name="android.permission.INTERNET" /> 

    <!-- Permission to write to external storage --> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
다음

AndroidLoadImageFromURLActivity.java 
package com.example.imagefromurl; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.ImageView; 

public class AndroidLoadImageFromURLActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     // Loader image - will be shown before loading image 
     int loader = R.drawable.loader; 

     // Imageview to show 
     ImageView image = (ImageView) findViewById(R.id.image); 

     // Image url 
     String image_url = "http://api.androidhive.info/images/sample.jpg"; 

     // ImageLoader class instance 
     ImageLoader imgLoader = new ImageLoader(getApplicationContext()); 

     // whenever you want to load an image from url 
     // call DisplayImage function 
     // url - image url to load 
     // loader - loader image, will be displayed before getting image 
     // image - ImageView 
     imgLoader.DisplayImage(image_url, loader, image); 
    } 
} 

그리고하여 ImageLoader 클래스

먼저 추가 다음의 액세스권 ..

//ImageLoader.java 
package com.example.imagefromurl; 

//import statement 

public class ImageLoader { 

    MemoryCache memoryCache=new MemoryCache(); 
    FileCache fileCache; 
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); 
    ExecutorService executorService; 

    public ImageLoader(Context context){ 
     fileCache=new FileCache(context); 
     executorService=Executors.newFixedThreadPool(5); 
    } 

    int stub_id = R.drawable.ic_launcher; 
    public void DisplayImage(String url, int loader, ImageView imageView) 
    { 
     stub_id = loader; 
     imageViews.put(imageView, url); 
     Bitmap bitmap=memoryCache.get(url); 
     if(bitmap!=null) 
      imageView.setImageBitmap(bitmap); 
     else 
     { 
      queuePhoto(url, imageView); 
      imageView.setImageResource(loader); 
     } 
    } 

    private void queuePhoto(String url, ImageView imageView) 
    { 
     PhotoToLoad p=new PhotoToLoad(url, imageView); 
     executorService.submit(new PhotosLoader(p)); 
    } 

    private Bitmap getBitmap(String url) 
    { 
     File f=fileCache.getFile(url); 

     //from SD cache 
     Bitmap b = decodeFile(f); 
     if(b!=null) 
      return b; 

     //from web 
     try { 
      Bitmap bitmap=null; 
      URL imageUrl = new URL(url); 
      HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
      conn.setConnectTimeout(30000); 
      conn.setReadTimeout(30000); 
      conn.setInstanceFollowRedirects(true); 
      InputStream is=conn.getInputStream(); 
      OutputStream os = new FileOutputStream(f); 
      Utils.CopyStream(is, os); 
      os.close(); 
      bitmap = decodeFile(f); 
      return bitmap; 
     } catch (Exception ex){ 
      ex.printStackTrace(); 
      return null; 
     } 
    } 

    //decodes image and scales it to reduce memory consumption 
    private Bitmap decodeFile(File f){ 
     try { 
      //decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      BitmapFactory.decodeStream(new FileInputStream(f),null,o); 

      //Find the correct scale value. It should be the power of 2. 
      final int REQUIRED_SIZE=70; 
      int width_tmp=o.outWidth, height_tmp=o.outHeight; 
      int scale=1; 
      while(true){ 
       if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
        break; 
       width_tmp/=2; 
       height_tmp/=2; 
       scale*=2; 
      } 

      //decode with inSampleSize 
      BitmapFactory.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize=scale; 
      return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
     } catch (FileNotFoundException e) {} 
     return null; 
    } 

    //Task for the queue 
    private class PhotoToLoad 
    { 
     public String url; 
     public ImageView imageView; 
     public PhotoToLoad(String u, ImageView i){ 
      url=u; 
      imageView=i; 
     } 
    } 

    class PhotosLoader implements Runnable { 
     PhotoToLoad photoToLoad; 
     PhotosLoader(PhotoToLoad photoToLoad){ 
      this.photoToLoad=photoToLoad; 
     } 

     @Override 
     public void run() { 
      if(imageViewReused(photoToLoad)) 
       return; 
      Bitmap bmp=getBitmap(photoToLoad.url); 
      memoryCache.put(photoToLoad.url, bmp); 
      if(imageViewReused(photoToLoad)) 
       return; 
      BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad); 
      Activity a=(Activity)photoToLoad.imageView.getContext(); 
      a.runOnUiThread(bd); 
     } 
    } 

    boolean imageViewReused(PhotoToLoad photoToLoad){ 
     String tag=imageViews.get(photoToLoad.imageView); 
     if(tag==null || !tag.equals(photoToLoad.url)) 
      return true; 
     return false; 
    } 

    //Used to display bitmap in the UI thread 
    class BitmapDisplayer implements Runnable 
    { 
     Bitmap bitmap; 
     PhotoToLoad photoToLoad; 
     public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;} 
     public void run() 
     { 
      if(imageViewReused(photoToLoad)) 
       return; 
      if(bitmap!=null) 
       photoToLoad.imageView.setImageBitmap(bitmap); 
      else 
       photoToLoad.imageView.setImageResource(stub_id); 
     } 
    } 

    public void clearCache() { 
     memoryCache.clear(); 
     fileCache.clear(); 
    } 

} 

그리고 전체 코드에 따라 해당 링크에 대한

..

http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

관련 문제