2016-03-28 77 views
0

我正在使用ViewPager來保存我的碎片。我有兩個分段查詢不同的碎片。我的片段之一有網格視圖佈局。我已經創建並適配GridView來加載圖像。ImageView內部NullPointerException適配器

這是我的片段

public class FeedsFragment extends Fragment { 
    GridView gridview; 
    List<ParseObject> ob; 
    FeedsGridAdapter adapter; 
    private List<ParseFeeds> phonearraylist = null; 
    View rootView; 

    public static final String TAG = FeedsFragment.class.getSimpleName(); 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     rootView = inflater.inflate(R.layout.feeds_layout, 
       container, false); 
     new RemoteDataTask().execute(); 
     return rootView; 
    } 


    private class RemoteDataTask extends AsyncTask<Void,Void,Void> { 

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

     @Override 
     protected Void doInBackground(Void... params) { 
      // Create the array 
      phonearraylist = new ArrayList<ParseFeeds>(); 
      try { 
       // Locate the class table named "SamsungPhones" in Parse.com 
       ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
         "AroundMe"); 
       // Locate the column named "position" in Parse.com and order list 
       // by ascending 
       // query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().getUsername()); 
       query.orderByAscending("createdAt"); 
       ob = query.find(); 
       for (ParseObject country : ob) { 
        ParseFile image = (ParseFile) country.get("videoThumbs"); 
        ParseFeeds map = new ParseFeeds(); 
        map.setPhone(image.getUrl()); 
        phonearraylist.add(map); 
       } 
      } catch (ParseException e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // Locate the gridview in gridview_main.xml 
      gridview = (GridView) rootView.findViewById(R.id.gridview); 
      // Pass the results into ListViewAdapter.java 
      adapter = new FeedsGridAdapter(FeedsFragment.this.getActivity(), 
        phonearraylist); 
      // Binds the Adapter to the ListView 
      gridview.setAdapter(adapter); 
     } 
    } 

} 

我創建的圖像加載到

public static final String TAG = FeedsGridAdapter.class.getSimpleName(); 

    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ImageLoader imageLoader; 
    private List<ParseFeeds> phonearraylist = null; 
    private ArrayList<ParseFeeds> arraylist; 

    public FeedsGridAdapter(Context context, List<ParseFeeds> phonearraylist) { 
     this.context = context; 
     this.phonearraylist = phonearraylist; 
     inflater = LayoutInflater.from(context); 
     this.arraylist = new ArrayList<ParseFeeds>(); 
     this.arraylist.addAll(phonearraylist); 
     imageLoader = new ImageLoader(context); 
    } 

    public class ViewHolder { 
     ImageView phone; 
    } 

    @Override 
    public int getCount() { 
     return phonearraylist.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return phonearraylist.get(position); 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    public View getView(final int position, View view, ViewGroup parent) { 
     final ViewHolder holder; 
     if (view == null) { 
      holder = new ViewHolder(); 
      view = inflater.inflate(R.layout.feeds_layout, null); 
      // Locate the ImageView in gridview_item.xml 
      holder.phone = (ImageView) view.findViewById(R.id.videoThumb); 
      view.setTag(holder); 
     } else { 
      holder = (ViewHolder) view.getTag(); 
     } 
     // Load image into GridView 
     imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), 
       holder.phone); 
     // Capture GridView item click 
     view.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // Send single item click data to SingleItemView Class 
       Intent intent = new Intent(context, SingleVideoView.class); 
       // Pass all data phone 
       intent.putExtra("phone", phonearraylist.get(position) 
         .getPhone()); 
       context.startActivity(intent); 
      } 
     }); 
     return view; 
    } 
} 

這裏它給我的NullPointerException上imageLoader.DisplayImage(phonearraylist.get(位置).getPhone適配器(), holder.phone);

當我在另一個項目中運行相同的代碼只有一個Fragment的工作,但是當我在當前項目中使用它與Two Fargments有不同的解析查詢時,它給了我NullPointerException.Please幫助我浪費了5天左右爲了讓它工作,儘可能在我的最後。

這裏是我的ImageLoader的類

MemoryCache memoryCache = new MemoryCache(); 
    FileCache fileCache; 
    private Map<ImageView, String> imageViews = Collections 
      .synchronizedMap(new WeakHashMap<ImageView, String>()); 
    ExecutorService executorService; 
    // Handler to display images in UI thread 
    Handler handler = new Handler(); 

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

    // int stub_id = ; 

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

    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); 

     Bitmap b = decodeFile(f); 
     if (b != null) 
      return b; 

     // Download Images from the Internet 
     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(); 
      conn.disconnect(); 
      bitmap = decodeFile(f); 
      return bitmap; 
     } catch (Throwable ex) { 
      ex.printStackTrace(); 
      if (ex instanceof OutOfMemoryError) 
       memoryCache.clear(); 
      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; 
      FileInputStream stream1 = new FileInputStream(f); 
      BitmapFactory.decodeStream(stream1, null, o); 
      stream1.close(); 

      // Find the correct scale value. It should be the power of 2. 
      final int REQUIRED_SIZE = 100; 
      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; 
      FileInputStream stream2 = new FileInputStream(f); 
      Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); 
      stream2.close(); 
      return bitmap; 
     } catch (FileNotFoundException e) { 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     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() { 
      try { 
       if (imageViewReused(photoToLoad)) 
        return; 
       Bitmap bmp = getBitmap(photoToLoad.url); 
       memoryCache.put(photoToLoad.url, bmp); 
       if (imageViewReused(photoToLoad)) 
        return; 
       BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); 
       handler.post(bd); 
      } catch (Throwable th) { 
       th.printStackTrace(); 
      } 
     } 
    } 

    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(R.drawable.camera_iris); 
     } 
    } 

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

} 
+0

首先將'imageLoader.DisplayImage'放入'if'條件中。我覺得'初始化'的問題 –

+0

首先需要找到斷點加載程序或您的圖像路徑與視圖尋呼機到底是什麼零頁 –

+0

你檢查了這裏** phonearraylist.get(position).getPhone()** you'r獲取圖片網址? – Piyush

回答

1

有一個NullPointerException imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone);

這導致了可疑空(ImageView) holder.phone

爲什麼它必須爲空?

因爲它可能不是躺在您膨脹到的視圖內。

所以

您應檢查您是否充氣從資源佈局合理,不作任何的最常見的錯誤就像使用活動/片段的佈局資源,而不是使用適配器的項目佈局。

不客氣。

+0

是的,我已經添加FeedFragment.this.getContext它解決了我的問題,非常感謝你的時間:) – Savita

+1

記住。有LayoutInflator時,您總是可以使用getBaseContext()。 – Mann

0

ImageLoader的初始化像下面這樣

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() 
    .cacheOnDisc()//.imageScaleType(ImageScaleType.EXACTLY) 
    .bitmapConfig(Bitmap.Config.RGB_565).build(); 
    ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
      this).defaultDisplayImageOptions(defaultOptions).memoryCache(
        new WeakMemoryCache()); 

    Display display = getWindowManager().getDefaultDisplay(); 
    Point size = new Point(); 
    display.getSize(size); 
    int width = size.x; 
    int height = size.y; 
    ImageLoaderConfiguration config = builder.build(); 
    imageLoader = ImageLoader.getInstance(); 
    imageLoader.init(config); 
+0

我應該用這段代碼替換它嗎? – Savita

+0

public void DisplayImage(String url,ImageView imageView){image02.jpg(imageView,url); 位圖bitmap = memoryCache.get(url);如果(位圖!=空) imageView.setImageBitmap(bitmap); else { queuePhoto(url,imageView); imageView.setImageResource(R.drawable.camera_iris); } } – Savita

+0

我應該怎樣做才能使用畢加索加載圖像? – Savita

相關問題