2014-03-19 3 views
0

URL의 특정 이미지를 ListView에로드하고 싶습니다. 하지만로드하는 동안 NullPointerException이 표시됩니다. JSON 응답을 반환하는 URL에서 데이터를 가져옵니다. 나는 응답을 HashMap으로 변환했다. 그러나 이미지를로드하는 동안 더 이상 NullPointerExceptionListView android의 URL에서 이미지로드

누군가가 해결책을 지적 할 수 있습니까? 덕분에 여기 내 코드입니다 : -

MainActivity.java

JSONArray jObject = new JSONArray(responseBody); 
          for (int i = 0; i < jObject.length(); i++) 
          { 
           JSONObject menuObject = jObject.getJSONObject(i); 
           String title= menuObject.getString("NewsSourceTitle"); 
           String description= menuObject.getString("Title"); 
           String thumbnail= menuObject.getString("ThumbnailPath"); 
           String newsUrl = menuObject.getString("Url"); 

            HashMap<String, String> map = new HashMap<String,String>(); 
            map.put(NEWSSOURCETITLE, title); 
            map.put(TITLE, description); 
            map.put(THUMBNAILPATH, thumbnail); 

            myNewsList.add(map); 


          } 
          itemsAdapter = new LazyAdapter(this, myNewsList); 
          newsList.setAdapter(itemsAdapter); 

LazyAdapter.java

 public class LazyAdapter extends BaseAdapter 
    { 
     private Activity activity; 
     private ArrayList<HashMap<String, String>> data; 
     private static LayoutInflater inflater = null; 
     public ImageLoader imageLoader; 

      public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) 
      { 
       activity = a; 
       data=d; 
       inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       imageLoader=new ImageLoader(); 
      } 

@Override 
    public int getCount() 
    { 
     // TODO Auto-generated method stub 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) 
    { 
     // TODO Auto-generated method stub 
     return position; 
    } 

    @Override 
    public long getItemId(int position) 
    { 
     // TODO Auto-generated method stub 
     return position; 
    } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) 
     { 
      View vi=convertView; 
      if(convertView==null) 
       vi = inflater.inflate(R.layout.list_row, null); 

      TextView title = (TextView)vi.findViewById(R.id.title); // title 
      TextView description = (TextView)vi.findViewById(R.id.description); // artist name 

      ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image 

      HashMap<String, String> song = new HashMap<String, String>(); 
      song = data.get(position); 

      // Setting all values in listview 
      title.setText(song.get("NewsSourceTitle")); 
      description.setText(song.get("Title")); 


      imageLoader.DisplayImage(song.get("ThumbnailPath"), thumb_image); 

      return vi; 
     } 

ImageLoader.java

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); 
    } 
    public ImageLoader() { 
     // TODO Auto-generated constructor stub 
    } 
    final int stub_id = com.zevenpooja.attini.R.drawable.myimage; 
    public void DisplayImage(String url, ImageView thumb_image) 
    { 
    // TODO Auto-generated method stub 
     imageViews.put(thumb_image, url); 
     Bitmap bitmap=memoryCache.get(url); 
     if(bitmap!=null) 
      thumb_image.setImageBitmap(bitmap); 
     else 
     { 
      queuePhoto(url, thumb_image); 
      thumb_image.setImageResource(stub_id); 
     } 

} 
    private void queuePhoto(String url, ImageView thumb_image) 
    { 
     // TODO Auto-generated method stub 
     PhotoToLoad p=new PhotoToLoad(url, thumb_image); // ERROR HERE 
     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); 
       URI uri = new URI(imageUrl.getProtocol(), imageUrl.getUserInfo(), imageUrl.getHost(), imageUrl.getPort(), imageUrl.getPath(), imageUrl.getQuery(), imageUrl.getRef()); 
       imageUrl = uri.toURL(); 
       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(); 
     } 

로그 캣

,
03-19 08:45:28.132: E/AndroidRuntime(3296): FATAL EXCEPTION: main 
03-19 08:45:28.132: E/AndroidRuntime(3296): java.lang.NullPointerException 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at Utility.ImageLoader.queuePhoto(ImageLoader.java:59) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at Utility.ImageLoader.DisplayImage(ImageLoader.java:50) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at Utility.LazyAdapter.getView(LazyAdapter.java:73) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.AbsListView.obtainView(AbsListView.java:2267) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1244) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.ListView.onMeasure(ListView.java:1156) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.View.measure(View.java:15172) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:681) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:574) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.View.measure(View.java:15172) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.View.measure(View.java:15172) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:833) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:574) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.View.measure(View.java:15172) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.View.measure(View.java:15172) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1848) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1273) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.Choreographer.doCallbacks(Choreographer.java:555) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.Choreographer.doFrame(Choreographer.java:525) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.os.Handler.handleCallback(Handler.java:615) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.os.Handler.dispatchMessage(Handler.java:92) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.os.Looper.loop(Looper.java:137) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at android.app.ActivityThread.main(ActivityThread.java:4745) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at java.lang.reflect.Method.invokeNative(Native Method) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at java.lang.reflect.Method.invoke(Method.java:511) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
03-19 08:45:28.132: E/AndroidRuntime(3296):  at dalvik.system.NativeStart.main(Native Method) 
+0

오류 로그를 제공 할 수 있습니까? – Cheerag

+0

@Cheerag 로그를 게시했습니다. 친절하게도 – user3354605

+0

은 MainActivity.java에서 문자열 상수 NEWSSOURCETITLE, TITLE 및 THUMBNAILPATH의 값을 나타냅니다 ??? – Antony

답변

0

충돌 로그는 또한 당신이 더 나은 성능을 얻을하는 데 도움이 될 것입니다이 발리 해방 https://developers.google.com/events/io/sessions/325304728 maby에 살펴보고, 더 많은 도움이 될 것입니다, 또한 내가 어댑터가이 방법도

@Override 
public int getCount() { 
     // TODO Auto-generated method stub 
     return data.size(); 
    } 

이 시도가없는 것을 볼

if(convertView==null) 
      vi = inflater.inflate(R.layout.list_row, parent,false); 
+0

위의 메서드를 사용했습니다. 코드를 자르므로 질문을 단순화 할 수 있습니다. – user3354605

+0

@ user3354605 정확한 코드와 충돌 로그를 제공하지 않을 때 도움이되는 훌륭한 솔루션입니다. –

+0

내 질문이 업데이트되었습니다. 제발 봐 – user3354605

관련 문제