1

I am displaying all images from storage of device in my app.The problem i am having is that when I am scrolling its not smooth.Its stucking inbetween.I am using etsy/AndroidStaggeredGrid and using below code.I tried putting tasks inside Async background Task but still i am having this issue. Why is it stucking inbetween and how can i resolve this?

GalleryFragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
    galleries=new ArrayList<Gallery>();
            ((ActionBarActivity) getActivity()).getSupportActionBar().show();
    gridview = (StaggeredGridView)rootView.findViewById(R.id.gridcamera);
    progressBar=(ProgressBar)rootView.findViewById(R.id.progressBar);
        gallerylist=new CameraGalleryAdapter(getActivity().getApplicationContext(), R.layout.gallery_grid,galleries);
    gridview.setAdapter(gallerylist);

    AsyncTaskRunner runner = new AsyncTaskRunner();

    runner.execute();

    return rootView;
}

private class AsyncTaskRunner extends AsyncTask<String, String, Void> {

    private String resp;

    @Override
    protected Void doInBackground(String... params)
    {

        int count,count2,count3,count4;

        ((CameraActivity)getActivity()).setOnBackPressedListener(new BaseBackPressedListener(getActivity(),true));

        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID,MediaStore.Video.Media.DATA,
        };
        final String orderBy = MediaStore.Images.Media._ID;
        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
                null, orderBy);

        count = cursor.getCount();
        Cursor cursor2 = getActivity().getContentResolver().query(
                MediaStore.Images.Media.INTERNAL_CONTENT_URI, columns, null,
                null, orderBy);
        count2 = cursor2.getCount();

        Cursor cursor3 = getActivity().getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null,
                null, orderBy);
        count3 = cursor3.getCount();
        Cursor cursor4 = getActivity().getContentResolver().query(
                MediaStore.Video.Media.INTERNAL_CONTENT_URI, columns, null,
                null, orderBy);
        count4 = cursor4.getCount();


        for (int i = 0; i < count; i++)
        {
            cursor.moveToPosition(i);
            int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

            Gallery ga=new Gallery();
            ga.setImageUrl(cursor.getString(dataColumnIndex));
            ga.setIsImage(true);
            galleries.add(ga);
        }
        for (int i = 0; i < count2; i++)
        {
            cursor2.moveToPosition(i);
            int dataColumnIndex = cursor2.getColumnIndex(MediaStore.Images.Media.DATA);
            Gallery ga=new Gallery();;
            ga.setImageUrl(cursor2.getString(dataColumnIndex));
            ga.setIsImage(true);
            galleries.add(ga);

        }

        for (int i = 0; i < count3; i++)
        {


            cursor3.moveToPosition(i);

            int dataColumnIndex = cursor3.getColumnIndex(MediaStore.Video.Media.DATA);

            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(cursor3.getString(dataColumnIndex),
                    MediaStore.Images.Thumbnails.MINI_KIND);

            Gallery ga=new Gallery();

            ga.setVideoThumbnail(thumb);

            ga.setVideoUrl(cursor3.getString(dataColumnIndex));

            ga.setIsImage(false);
            galleries.add(ga);


        }
        for (int i = 0; i < count4; i++)
        {


            cursor4.moveToPosition(i);

            int dataColumnIndex = cursor4.getColumnIndex(MediaStore.Video.Media.DATA);

            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(cursor4.getString(dataColumnIndex),MediaStore.Images.Thumbnails.MINI_KIND);

            Gallery ga = new Gallery();

            ga.setVideoThumbnail(thumb);

            ga.setVideoUrl(cursor4.getString(dataColumnIndex));

            ga.setIsImage(false);
            galleries.add(ga);


        }
        return null;
    }



    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        gallerylist.notifyDataSetChanged();
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onProgressUpdate(String... text) {

    }
}

CameraGalleryAdapter

public class CameraGalleryAdapter extends BaseAdapter {
    ArrayList<Gallery> itemList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;
    Bitmap bm;
    public CameraGalleryAdapter(Context context, int resource, ArrayList<Gallery> objects) {

        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        itemList = objects;

    }


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

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {

        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImageg);
            holder.playicon= (ImageView) v.findViewById(R.id.galleryplay);

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

 if(itemList.get(position).getIsImage())
 {

            holder.playicon.setVisibility(View.INVISIBLE);

     AsyncTaskRunner runner = new AsyncTaskRunner();

     runner.execute(itemList.get(position).getImageUrl());
     bm= null ;
     try {
         bm = runner.get();
     } catch (InterruptedException e) {
         e.printStackTrace();
     } catch (ExecutionException e) {
         e.printStackTrace();
     }
     holder.imageview.setImageBitmap(bm);
 }
 else
 {
            holder.playicon.setVisibility(View.VISIBLE);
            holder.imageview.setImageBitmap(itemList.get(position).getVideoThumbnail());
 }
        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public ImageView playicon;

    }
    private class AsyncTaskRunner extends AsyncTask<String, String,Bitmap>
    {

        private String resp;

        @Override
        protected Bitmap doInBackground(String... params)
        {
            resp=params[0];
            Bitmap bm = decodeSampledBitmapFromUri(resp, 220, 220);
            return bm;
        }



        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(Bitmap aVoid) {
            super.onPostExecute(aVoid);


        }

        @Override
        protected void onProgressUpdate(String... text) {

        }
    }
    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

        Bitmap bm = null;

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);


        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);


        options.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeFile(path, options);

        return bm;
    }

    public int calculateInSampleSize(

            BitmapFactory.Options options, int reqWidth, int reqHeight)
    {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float)height / (float)reqHeight);
            } else {
                inSampleSize = Math.round((float)width / (float)reqWidth);
            }
        }

        return inSampleSize;
    }

}
Android Developer
  • 9,157
  • 18
  • 82
  • 139
  • its a common issue bcoz of large Image size is loading in a view each time you scroll .... to over come this issue you can try lazy Loading imgae technique.. http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134 – koutuk Jun 19 '15 at 11:55
  • Using a AsyncTask won't help much when you get the result by calling `.get()`. the `get` call blocks execution on the main thread until the image is loaded. This is probably the lag you're experiencing. – M4rtini Jun 19 '15 at 11:59
  • possible duplicate of [Smooth scrolling in Android](http://stackoverflow.com/questions/4951142/smooth-scrolling-in-android) – King of Masses Jun 19 '15 at 12:02
  • @M4rtini even if i don't use AsyncTask it is stucking inbetween while scrolling – Android Developer Jun 19 '15 at 12:14
  • @KingofMasses in the link u provided i see using GestureDetector..can u write in answer how i have to use it with my gridview to make it scroll smoothly? – Android Developer Jun 19 '15 at 12:17
  • You need to delay setting the image of the imageview until the image is loaded, usually in `onPostExecute`. Passing the imageview to the asynchTask should allow for that to be done there. And remove the `get` call. And you may want to assign a placeholder image for while the asyncTask is loading the image. – M4rtini Jun 19 '15 at 12:20
  • @BhuvneshVarma both have common adapter type you just need to modify your getview method.... – koutuk Jun 19 '15 at 12:28
  • Yes it can easily loadable via sdcard using uri – koutuk Jun 19 '15 at 12:29
  • @koutuk okay i added the required files and now using `imageLoader.DisplayImage(itemList.get(position).getImageUrl(),holder.imageview);` to load images but now the images are not loading..are u sure for static images also we need to follow same procedure?Here `itemList.get(position).getImageUrl(),` is path of image in storage – Android Developer Jun 19 '15 at 12:57
  • @koutuk thanks..worked..if u can write your first comment properly in answer i can select it as best answer.. – Android Developer Jun 21 '15 at 09:14

1 Answers1

1

its a common issue bcoz of large Image size is loading in a view each time you scroll .... to over come this issue you can try lazy Loading imgae technique.. http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134

koutuk
  • 832
  • 1
  • 8
  • 17