Thursday 7 January 2016

Volley Network Image Loader to manage your GridView images



Volley Library

Volley is an HTTP library that makes networking for Android apps easier and faster. Volley is available through the open AOSP repository. Volley Library is developed by the Google developers, but its not officailly launched by the Google. Google Application uses this library in there apps.



Here are some of the advantages of volley library:

  • Automatic scheduling of network requests.
  • Multiple parallel operation on network connection
  • You can also prioritize your requests
  • You can also cancel the requests
To get started you need to clone the Volley Library from the repository.



How to clone library?

I would suggest you to download the Git from this link. Download here
After downloading install it. 
  • Open Git-Gui. 
  • Go to Repository Clone or simply press Ctrl+L
  • Copy and paste this in the Source location.
git clone https://android.googlesource.com/platform/frameworks/volley

  • Set your target directory.
  • Or you can run this command from command prompt or from Git Bash.
Once cloning finished successfully, now you need to import that project into your project in order to use that library in your project.

Here are the steps to import library in the Android Studio.

  • Open the project in which you want to use the Volley Library.
  • Go to File New Import Module give the path of the volley directory you cloned which you have cloned from the repository and follow the further steps. After completing the desired steps the volley folder should be displayed in your project hierarchy in the left.
And here you have successfully imported the library in your project.
After successfully import of the Volley Library, here I will show how to load images in the gridview from the network. Below is the full code for that.



Here in the example I will show that how to load the images from the multiple url in your gridview from the internet.

 
1)  MainActivity.java

package com.app.srcecde.grid;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;



import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class MainActivity extends AppCompatActivity {

    private GridView g;
    ImageLoader mImageLoader;
    NetworkImageView mNetworkImageView;

    static final String[] imagesurl = new String[]{
            "http://url1", //replace with the url
            "http://url2",
            "http://url3"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        g= (GridView) findViewById(R.id.grid);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        mImageLoader = MyVolleySingleton.getInstance(this).getImageLoader();

        final GridView gridView = (GridView) findViewById(R.id.grid);
        gridView.setAdapter(new MyImageAdapter());


    }

    static class ViewHolder {
        ImageView imageView;
    }



    class MyImageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return imagesurl.length;
        }

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

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

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

            View view = convertView;
            final ViewHolder gridViewImageHolder;

            try
            {
                if (view == null) {
                    view = getLayoutInflater().inflate(R.layout.activity_main, parent, false);
                    gridViewImageHolder = new ViewHolder();
                    gridViewImageHolder.imageView = (ImageView) view.findViewById(R.id.network);
                    view.setTag(gridViewImageHolder);
                } else {
                    gridViewImageHolder = (ViewHolder) view.getTag();
                }

                mNetworkImageView = (NetworkImageView) gridViewImageHolder.imageView;
                mNetworkImageView.setDefaultImageResId(R.mipmap.ic_launcher);
                mNetworkImageView.setErrorImageResId(R.mipmap.ic_launcher);
                mNetworkImageView.setAdjustViewBounds(true);
                mNetworkImageView.setImageUrl(imagesurl[position], mImageLoader);
            }
            catch (Exception e)
            {

            }
            return view;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2)  MyVolleySingleton.java

package com.app.srcecde.grid;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

/**
 * Created by SrceCde on 07-01-2016.
 */
public class MyVolleySingleton {
    private static MyVolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private MyVolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized MyVolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MyVolleySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}

3)  LruBitmapCache.java


package com.app.srcecde.grid;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;

import com.android.volley.toolbox.ImageLoader;

/**
 * Created by SrceCde on 07-01-2016.
 */
public class LruBitmapCache extends LruCache<String, Bitmap>
        implements ImageLoader.ImageCache {

    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }

    public LruBitmapCache(Context ctx) {
        this(getCacheSize(ctx));
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }

    // Returns a cache size equal to approximately three screens worth of images.
    public static int getCacheSize(Context ctx) {
        final DisplayMetrics displayMetrics = ctx.getResources().
                getDisplayMetrics();
        final int screenWidth = displayMetrics.widthPixels;
        final int screenHeight = displayMetrics.heightPixels;
        // 4 bytes per pixel
        final int screenBytes = screenWidth * screenHeight * 4;

        return screenBytes * 3;
    }
}

4)  activity_content.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent">

    <com.android.volley.toolbox.NetworkImageView
        android:layout_width="200dp"
        android:id="@+id/network"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        />
    <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/grid"
        android:numColumns="2">
    </GridView>
</RelativeLayout>


Also you need to add INTERNET permission in AndroidManifest. xml
MyVolleySingleton.java and LruBitmapCache.java is referenced from Android developer site

Note: Replace the imageurl in MainActivity.java with your actual url.

Stay tuned and subscribe to my blog and my channel "Srce Cde" on YouTube for more fun. You are welcome to ask your question in comments.

No comments:

Post a Comment