2

I want to use preloader image in gridview for images when its loading form the remote server. while its loading from the server at that time i want to show preloader image like this(same like progress bar or progress bar).

I want to show small progress bar there in gridview image item or preloader image I dnt know what i can use which would be easily for me to achieve this.

Can anybody please help me how can do this thing in android.

I want to make this as like IOS. this image is form the IOS.

enter image description here

Here is my android layout xml file :

activity_image_grid.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <include
        android:id="@+id/title_bar"
        android:layout_alignParentTop="true"
        layout="@layout/activity_top_header_bar" />

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/title_bar"
        android:gravity="center"
        android:horizontalSpacing="4dip"
        android:numColumns="4"
        android:padding="5dip"
        android:stretchMode="columnWidth"
        android:verticalSpacing="4dip" />

</RelativeLayout>

This xml file used for item for each grid in Gridview.

item_grid_image.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="75dp"
    android:adjustViewBounds="true"
    android:contentDescription="@string/descr_image"
    android:scaleType="centerCrop" />

Source code :

public class ImageGridActivity extends BaseActivity {
    private static final String TAG = "[ImageGridActivity]";

    private DisplayImageOptions options;

    private PullToRefreshGridView mPullRefreshGridView;

    private GridView mGridView = null;
    ArrayList<GallaryImage> mGridViewImagesList;
    private ImageAdapter mImageAdapter = null;

    private String mImageUrl = null;
    private String mGallaryTitle = null;

    // private ImageLoader imageLoader = ImageLoader.getInstance();

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_grid);
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.photo_default)
                .showImageForEmptyUri(R.drawable.photo_default)
                .showImageOnFail(R.drawable.ic_error).cacheInMemory()
                .cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();

        final Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mImageUrl = bundle.getString(Constants.GALLARY_FETCH_URL);

            mGallaryTitle = bundle.getString(Constants.GALLARY_TYPE);
            if (mGallaryTitle != null) {

                Locale loc = Locale.getDefault();
                TextView tvTitleText = (TextView) findViewById(R.id.tv_title_bar_text);
                tvTitleText.setText(mGallaryTitle.toUpperCase(loc));
            }

            mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
            mPullRefreshGridView.setMode(Mode.PULL_FROM_START);
            mGridView = mPullRefreshGridView.getRefreshableView();

            mGridViewImagesList = Utility.getImagesList(mImageUrl,
                    ImageGridActivity.this);

            if (mGridViewImagesList != null && !mGridViewImagesList.isEmpty()) {
                mImageAdapter = new ImageAdapter(mGridViewImagesList);
                ((GridView) mGridView).setAdapter(mImageAdapter);
            } else {
                // did refresh after the previous images are loaded in the
                // gridview.
                if (Utility.checkConnection(ImageGridActivity.this)) {
                    Log.i(TAG,
                            "Wifi/Internet Connection found , have to parse the xml");

                    final FetchImagesAsyncTaskFeed asyncTask = new FetchImagesAsyncTaskFeed();
                    asyncTask.execute(mImageUrl);

                }

            }

            mGridView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(final AdapterView<?> parent,
                        final View view, final int position, final long id) {

                    if (mGridViewImagesList != null
                            && !mGridViewImagesList.isEmpty()) {
                        startImagePagerActivity(mGridViewImagesList, position);
                    } else {
                        Log.d(TAG, "There is no image about this grid image");
                    }
                }
            });

            // Set a listener to be invoked when the list should be refreshed.
            mPullRefreshGridView
                    .setOnRefreshListener(new OnRefreshListener2<GridView>() {

                        @Override
                        public void onPullDownToRefresh(
                                PullToRefreshBase<GridView> refreshView) {
                            if (mImageUrl != null) {
                                final FetchImagesAsyncTaskFeed asyncTask = new FetchImagesAsyncTaskFeed();
                                asyncTask.execute(mImageUrl);
                            }
                        }

                        @Override
                        public void onPullUpToRefresh(
                                PullToRefreshBase<GridView> refreshView) {

                        }
                    });

        }

    }

    /**
     * @param position
     */
    private void startImagePagerActivity(
            final ArrayList<GallaryImage> mImageAttributesList,
            final int position) {
        String[] urls = new String[mImageAttributesList.size()];
        final Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(Constants.GALLARY_IMAGE_POSITION_BUNDLE_KEY, position);
        for (int i = 0; i < mImageAttributesList.size(); i++) {
            urls[i] = mImageAttributesList.get(i).mImageUrl;
        }
        intent.putExtra(Constants.GALLARY_IMAGES_IMAGE_BUNDLE_KEY, urls);
        startActivity(intent);
    }

    public class ImageAdapter extends BaseAdapter {
        ArrayList<GallaryImage> imageList = null;

        public ImageAdapter(final ArrayList<GallaryImage> imageAttributesList) {
            this.imageList = imageAttributesList;

        }

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

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

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

        @Override
        public View getView(final int position, final View convertView,
                final ViewGroup parent) {
            final ImageView imageView;
            if (convertView == null) {
                imageView = (ImageView) getLayoutInflater().inflate(
                        R.layout.item_grid_image, parent, false);
            } else {
                imageView = (ImageView) convertView;
            }

            imageLoader.displayImage(imageList.get(position).mImageUrl,
                    imageView, options);

            return imageView;
        }

        /**
         * @param updateData
         */
        public void updatedData(ArrayList<GallaryImage> imgList) {
            this.imageList = imgList;
            notifyDataSetChanged();
        }
    }

    private class FetchImagesAsyncTaskFeed extends
            AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(final String... urls) {
            try {
                Thread.sleep(3000);
                final String imageUrl = urls[0];
                final GridViewImagesXMLHandler mGallaryXMLHandler = new GridViewImagesXMLHandler();
                mGridViewImagesList = mGallaryXMLHandler.getImages(imageUrl);
                if (mGridViewImagesList != null
                        && !mGridViewImagesList.isEmpty()) {
                    Utility.setImagesInfromation(imageUrl, mGridViewImagesList,
                            ImageGridActivity.this);
                }
            } catch (final Exception e) {
                Log.e(TAG, "Exception in fetch images from the url", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String result) {
            if (mGridViewImagesList != null && !mGridViewImagesList.isEmpty()) {
                if (mImageAdapter != null) {
                    mImageAdapter.updatedData(mGridViewImagesList);
                    mPullRefreshGridView.onRefreshComplete();
                } else {
                    mImageAdapter = new ImageAdapter(mGridViewImagesList);
                    ((GridView) mGridView).setAdapter(mImageAdapter);
                }
            }
            mPullRefreshGridView.onRefreshComplete();
        }
    }
}
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
sam_k
  • 5,983
  • 14
  • 76
  • 110
  • http://stackoverflow.com/questions/15621936/whats-lazylist. use lazy list or Universal Image Loader. Check the link. – Raghunandan May 04 '13 at 09:14
  • @Raghunandan MY question is different i want to show progress bar type image or progress bar on each and every imageview while its loading from the remote server – sam_k May 04 '13 at 10:08
  • yes it is possible using Universal Image Loader – Raghunandan May 04 '13 at 10:12
  • hows it possible? I have image loader library with its sample code.. There is no Progress bar i had seen in GridView activity – sam_k May 04 '13 at 10:14
  • i will post an answer wait – Raghunandan May 04 '13 at 10:15
  • @Raghunandan https://raw.github.com/nostra13/Android-Universal-Image-Loader/master/UniversalImageLoader.png Its show android image by default. Here in my case i have default image that is no matter but i want to overlay one progress bar while its loading same like posted image. – sam_k May 04 '13 at 10:15

2 Answers2

1

Universal ImageLoader

https://github.com/nostra13/Android-Universal-Image-Loader

rowimage.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/ivv"
    android:layout_gravity="center"
    android:layout_width="300dp"
    android:layout_height="300dp"

    />
<ProgressBar 
    android:id="@+id/pb"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

In your adapter constructor

       ImageLoader imageLoader; 
       DisplayImageOptions options;  

      File cacheDir = StorageUtils.getOwnCacheDirectory(a, "MyRaghu");


 // Get singletone instance of ImageLoader
   imageLoader = ImageLoader.getInstance();
 // Create configuration for ImageLoader (all options are optional)
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
              // You can pass your own memory cache implementation
             .discCacheExtraOptions(1024, 1024, CompressFormat.PNG, 100)
             .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
             .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
             .enableLogging()
             .build();
 // Initialize ImageLoader with created configuration. Do it once.
 imageLoader.init(config);
    //imageLoader.init(ImageLoaderConfiguration.createDefault(a));
   // imageLoader=new ImageLoader(activity.getApplicationContext());
    options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.ic_launcher)
    .cacheInMemory()
    .cacheOnDisc()
    .displayer(new RoundedBitmapDisplayer(20))
    .build();

In your getview of your custom adapter

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

    ImageView image=(ImageView)vi.findViewById(R.id.ivv); 
    ProgressBar pb= (ProgressBar)vi.findViewById(R.id.pb); 
    display(null, data.get(position).toString(), pb);
    //imageLoader.displayImage(data.get(position).toString(), image,options);

    return vi;
}

public void display(ImageView img, String url, final ProgressBar spinner)
{
    imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
         spinner.setVisibility(View.VISIBLE);
        }
        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
         spinner.setVisibility(View.GONE);


        }
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)                      {
         spinner.setVisibility(View.GONE);
        }
        @Override
        public void onLoadingCancelled(String imageUri, View view) {

        }

});
}

Resulting snap shot i have used listview but it should work for gridview also.

First a stub image is displayed along with progress bar. In this case a i have used a launcher icon so it looks stretched

Once image is downloaded progress bar is dismissed and stub image is replaced by the downloaded one. Even caches images.

enter image description here

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • thanks for your answer.. I will check this answer with code. Can i use different progress as like above here in android? – sam_k May 04 '13 at 10:37
  • http://upadhyayjiteshandroid.blogspot.in/2013/02/android-custom-progress-bar.html. if you google you will find more. – Raghunandan May 04 '13 at 10:43
  • I have also one more question open on Stack overflow. Can u please look at there its really a big question..I integrated UIL and ImageViewTouch but i am getting issue in this. It works fine but have little issue. http://stackoverflow.com/questions/16341313/how-to-fit-image-in-full-screen-in-imageviewtouch – sam_k May 04 '13 at 10:45
  • i am not sure how to solve the problem in the link u posted in the comment. If the answer helps pls accept the same. You can use a photoview https://github.com/chrisbanes/PhotoView. not sure how to integrate the same with UIL. i have not tried. – Raghunandan May 04 '13 at 10:55
  • I will Accept once it will work. Please take a look at my above question link i updated my question – sam_k May 04 '13 at 10:59
  • Here i have one question? From where i will get this method `public void display(ImageView img, String url, final ProgressBar spinner) {` with all override methods? – sam_k May 04 '13 at 12:21
  • u override that method when u use UIL – Raghunandan May 04 '13 at 13:21
  • Only these `public void displayImage(String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) public void displayImage(String uri, ImageView imageView, ImageLoadingListener listener) public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) public void displayImage(String uri, ImageView imageView) ` Methods are there where is the method with Progressbar argument? Please give me idea how can i override this method? – sam_k May 04 '13 at 13:24
  • @Sam_k i have tried tested and then posted the same as an answer. R u sure u are using UIL. Coz the above works for me – Raghunandan May 04 '13 at 13:27
  • i wrote a display function to pass the progress bar as a parameter. inside the display function i call the method under complete in the link https://github.com/nostra13/Android-Universal-Image-Loader. Now that method has @Override public void onLoadingStarted(String imageUri, View view) { spinner.setVisibility(View.VISIBLE); } and then i dismiss when loading completes – Raghunandan May 04 '13 at 13:33
0

Try to use Android-Universal-Image-Loader api from github.com

Android-Universal-Image-Loader

I think it help you.

Thanks.

Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
  • I already use this one.. I already used android Universal Image Loader things in my code.. – sam_k May 04 '13 at 09:50
  • but here my question is i want to show that preloader image while its downloading image from the remote server – sam_k May 04 '13 at 09:51