Android Volley Library Example/Tutorial
Volley networking library is used to make networking calls much easier and in less code.Earlier we need to make networking calls asynchronously to avoid NetworkOnMainThread Exception.In Volley, we don’t need to worry about NetworkOnMainThread Exception as it handles all calls automatically asynchronously.
Volley is used due to following features: –
1.It uses cache memory thus loading images from server much faster.
2.We can queue and prioritize the requests in Volley.
3.Managing JSON APi requests.
4.Cancelling the requests.
Other Alternatives of Volley are: –
1.Picasso Library – Android use Picasso Image Loader Library.
2.Glide Library- Android Working with Glide Image Loader Library.
So, Let’s start how to use Volley Library.
1.Open Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.
2. To use Volley in our application we need to add the following dependency in build.gradle
compile 'com.mcxiaoke.volley:library:1.0.19'
3. Now add NetworkImageView in your layout where you want to load Images from the server.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/maintext" android:layout_alignParentTop="true" android:text="Loading image from url using Volley Library " android:layout_width="fill_parent" android:layout_height="wrap_content" /> <com.android.volley.toolbox.NetworkImageView android:id="@+id/imagetoload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/maintext" /> </RelativeLayout>
4. Now Create a class for requesting queue like this.
MyVolleyRequest.java
package com.coderzpassion.volleyimagesample; import android.content.Context; import android.graphics.Bitmap; import android.util.LruCache; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; /** * Created by coderzpassion on 02/03/16. */ public class MyVolleyRequest { private static MyVolleyRequest myVolleyRequest; private static Context context; private RequestQueue requestQueue; private ImageLoader imageLoader; public MyVolleyRequest(Context con) { this.context=con; this.requestQueue=requestMyQueue(); imageLoader=new ImageLoader(requestQueue,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 MyVolleyRequest getInstance(Context con) { if(myVolleyRequest==null) return new MyVolleyRequest(con); return myVolleyRequest; } public RequestQueue requestMyQueue() { if(requestQueue==null) { Cache cache=new DiskBasedCache(context.getCacheDir(),10*1024*1024); Network network=new BasicNetwork(new HurlStack()); requestQueue=new RequestQueue(cache,network); requestQueue.start(); } return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } }
5. Now create MainActivity.java to load the image using volley from server
MainActivity.java
package com.coderzpassion.volleyimagesample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; public class MainActivity extends AppCompatActivity { NetworkImageView networkImageView; private ImageLoader imageLoader; String url="http://coderzpassion.com/wp-content/uploads/2016/03/coderzpassion.png"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); networkImageView=(NetworkImageView)findViewById(R.id.imagetoload); imageLoader=MyVolleyRequest.getInstance(MainActivity.this).getImageLoader(); imageLoader.get(url,imageLoader.getImageListener(networkImageView,R.mipmap.ic_launcher,android.R.drawable.stat_notify_error)); networkImageView.setImageUrl(url,imageLoader); } @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); } }
6. Important Point: – Don’t forget to add INTERNET permission in your AndroidManifest.xml
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.coderzpassion.volleyimagesample" > <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Output