Android Custom ListView Tutorial Using Volley

TUTORIAL ON CUSTOM LISTVIEW USING VOLLEY IN ANDROID STUDIO.


This tutorial will show you how to create an Android Custom ListView Using Volley and loading images in ListView from server and cache them so they can instantly be available after download. We are using third party library volley which provides an efficient way to get data and images from the server.


Agenda:-

1.      What is Volley Library?

2.     What is JSON?

3.     What is Custom ListView?

4.     Build Simple APP Using Volley Library, JSON, and Custom ListView.

So let’s start.

1: What is Volley?

  • Volley is a networking library developed by Google and introduced during Google I/O 2013 networking class capable of working without user interfering.
  • Until the release of Volley, the Apache and canonical Java class java.net.HttpURLConnection were the only available tools for the communication between a client with the backend.

Why Volley?

  • Avoid HttpUrlConnection and HttpClient.
  • Avoid AsyncTask, too.
  • It’s much faster.
  • Small Metadata operations.

Using Volley

  • Volley mostly works with just two classes, RequestQueue and Request. First, you have to create a RequestQueue, which manages worker threads and delivers the parsed results back to the main thread. You then pass it one or more Request objects.
  • When you create an object of Request class, it will take four parameters: the method type (GET, POST, etc.), the URL of the resource, and event listeners. Then, depending on the type of request, it may ask for some more variables.

Importing Volley

Download the Volley source from its repository. If you feel confident doing this, this Git command can do all the work for you:

https://android.googlesource.com/platform/frameworks/volley

There is another way as well; Add following line in the dependency of the build.gradle:

compile 'com.mcxiaoke.volley:library-aar:1.0.15

Three Main Classes for VOLLEY:

1: REQUESTQUEUE.

The most important and easy way to use Volley for a network in an android application is to create a set up a single object of RequestQueue for the complete lifecycle of Android application. To achieve this, we have to either create a separate singleton class and add the RequestQueue object as member field and create methods to achieve the functionality offered by Volley or rather than creating a separate class you just have to create a RequestQueue object.

Syntax:

RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
  1. Create a RequestQueue object by invoking one of Volley’s convenience methods, Volley.newRequestQueue. This sets up a RequestQueue object, using default values defined by Volley.
  2. By doing this, it will allow us to do the JSON request and all another URL request to be managed concurrently.
  3. If we are using RequestQueue class, we don’t have to make AsyncTask class as we did before to parse JSON data.

2: REQUEST.

  • A Base Class which contains Network related information like HTTP Methods.
  • Volley has Request for JsonObject and JsonArray.
Syntax: 

JsonObjectRequest request=new JsonObjectRequest(Method.GET,url,null,new ResponseListener(),new ErrorListener());
  • The first parameter of the constructor is the HTTP method to use (GET,POST,ETC).
  • The second parameter provides the URL for fetching the JSON from.
  • The third variable in the example above is null. This is fine as it indicates that no parameters will be posted along with the request.
  • The fourth parameter is a listener to receive the JSON response and an error listener.
“You can ask for a JSONArray, too, if you want using a JsonArrayRequest instead of a JsonObjectRequest.”

3: IMAGELOADER.

  • This is the helper class that handles LOADING and CACHING IMAGES from URLs.Valley also offers basic images handling requests. Specify a URL and receive an image in response.
  • ImageLoader is to arrange for large numbers of ImageRequests. For example, when storing multiple images in a ListView, ImageLoader provides an in-memory cache as Volley cache.

Syntax:

ImageRequest request = new ImageRequest(url,new Response.Listener<Bitmap>(){},new Response.ErrorListener(){});
  1. The first parameter is the URL of the picture.
  2. The second one is the listener for the result.
  3. The third one we pass in an error listener.

2: What is JSON?

JSON (JAVASCRIPT OBJECT NOTATION) is a lightweight data-interchange format. It is easy to read and write for a human. We use JSON because it is easy to access and much easier to read. In JSON we have key value pairs.The data from JSON have 2 parts; a key and a value. JSON consists of two types of points, objects, and arrays.

Below is the example of JSON data.

[
{
"name": "First Richman",
"image": " https://raw.githubusercontent.com/iCodersLab/Custom-ListView-Using-Volley/master/images/Bill_Gates.jpg",
"worth": "$79.2 billion",
"InYear": 2015,
"source": "Microsoft"
}
]
Here is the URL, you can see.

https://raw.githubusercontent.com/iCodersLab/Custom-ListView-Using-Volley/master/richman.json
  • As shown above, curly brackets represent object, and square brackets represent an array. In JSON, the point (node) starts from ‘{‘ use getJSONObject() method and or your point (node) starts with ‘[‘ use getJSONArray() method.

3: What is Custom ListView?

  • Custom ListView is used to create dynamic Listview which has image and text with a custom adapter in android.
  • Also described is the context of menu and click or event listeners. For custom ListView, we have to create Adapter or extend the CustomListView class with BaseAdapter.

4: Build Simple APP Using VolleyLibrary, JSON, and Custom ListView.

Let’s start. Before we begin, I’m assuming you have a properly working android studio.

1. Create a Project.

  • Go to files and create a new project with an empty activity and name it.Android Custom ListView Using Volley 1

2. Go to AndroidManifest.xml to Add Internet Access to Your App:

  • As we are fetching our JSON data from a URL, we need to have internet access permission in our application.
<uses-permission android:name=”android.permission.INTERNET”/>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="volleylistview.com.icoderslab.volleylistview">
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:name="volleylistview.com.icoderslab.icoderslab.com.volleylistview.Controller"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="volleylistview.com.icoderslab.icoderslab.com.volleylistview.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>

3. Edit your MainActivity.xml file.

  • Go to Android/res/layout/MainActivity.xml. (My file name is activity_main.xml)
  • Add a relative layout and a list view, either drag and drop or by XML code
  • Below is the XML code. (Your code should look similar to this).
<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"
tools:context=".MainActivity"><ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:background="#ef2505"/>
</RelativeLayout>

4. Create Another XML File for Showing Data.

  • Now you need to add listview row XML file where we will show data.
  • Go to layout-> right click go to New-> add Layout Resource File-> name your XML file and click ok.
  • Add 4 TextViews and 1 NetworkImageView within RelativeLayout.
<?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"
    android:padding="8dp"
    android:background="#cf7f7f"
    >

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="15dp"
        android:textColor="#575294"
        android:textStyle="bold"
        android:fontFamily="sans-serif-condensed"
        />

    <TextView
        android:id="@+id/worth"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="15dp"
        android:textColor="#575294"
        android:fontFamily="sans-serif-condensed"

        />

    <TextView
        android:id="@+id/source"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/worth"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="15dp"
        android:textColor="#575294"
        android:fontFamily="sans-serif-condensed"

        />

    <TextView
        android:id="@+id/inYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:textSize="15dp"
        android:textColor="#f9f9f9"
        android:fontFamily="sans-serif-condensed"

        />

</RelativeLayout>

5.  Go to MainActivity.java file:

  • This class contains JsonArrayRequest with their attributes.
  • In this class, we are parsing data from URL.

Here, I am using above JSON’s link as example.

package volleylistview.com.icoderslab.volleylistview;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
* Created by Hatesh kumar on 11/07/2016.
*/

public class MainActivity extends Activity {

private static final String tag = MainActivity.class.getSimpleName();
private static final String url = "https://raw.githubusercontent.com/iCodersLab/Custom-ListView-Using-Volley/master/richman.json";
private List<DataSet> list = new ArrayList<DataSet>();
private ListView listView;
private Adapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.list);
adapter = new Adapter(this, list);
listView.setAdapter(adapter);


JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {

for (int i = 0; i < response.length(); i++) {
try {

JSONObject obj = response.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(obj.getString("name"));
dataSet.setImage(obj.getString("image"));
dataSet.setWorth(obj.getString("worth"));
dataSet.setYear(obj.getInt("InYear"));
dataSet.setSource(obj.getString("source"));
list.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}

}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getPermission().addToRequestQueue(jsonreq);
}

}

Description of code:

  • We created an object of Adapter class which is used to add data on.
  • We have created the object of JsonObjectRequest and also passed the parameter in the JsonObjectRequest class.
  • Now I will tell you one by one how and why we passed each parameter.
  • The first parameter is URL from where we want to parse our data.
  • The second parameter is Listener. Here we have passed the Response. A listener which will override the method onResponse() and passed JSONObject as a parameter. onResponse()method take the response from the JSON data requested by a user.
  • Here we are using for loop to get the JSON Objects from JSON Array. This for loop works until all the JSON objects are parsed.
  • We are creating the object of JSONObject() class . This will get the each object from the JSON array continuously.
  • Here we created the object of DataSet class which is user built in class.
  • Here we are retrieving the data from JsonArray using JsonObject and passing it to a method which is basically in DataSet class.
  • The third and the last parameter is ErrorListener . The Response.ErrorListener which will override the method onErrorResponse() and gives the VolleyError variable for any Exception. onErrorResponse() method handle the error occurs due to volley library.
  • To send a request, add JsonRequest object to the requestQueuewith add().
  • Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.

 

6. Create DataSet.java file.

  • This class holds object after parsing to provide data to ListView.
package volleylistview.com.icoderslab.volleylistview;


/**
* Created by Hatesh kumar on 11/07/2016.
*/

public class DataSet {

private String name, image;
private int year;
private String source;
private String worth;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}

public String getSource() {
return source;
}

public void setSource(String source) {
this.source = source;
}

public String getWorth() {
return worth;
}

public void setWorth(String worth) {
this.worth = worth;
}
}

Description of code:

“This class is straightforward to understand, so I am not going to describe this class because you already know about methods in java so let’s skip description and move on another part of App.”

 

7. Create Adapter.java file.

  •  This class contains adapter for our listview and will show our data.
  •  It is custom list adapter which renders each row of ListView, getView method is called for each row, which uses list_row.xml as view and fills it with the appropriate data.
package volleylistview.com.icoderslab.volleylistview;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

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

import java.util.List;


/**
* Created by Hatesh kumar on 11/07/2016.
*/

public class Adapter extends BaseAdapter {

private Activity activity;
private LayoutInflater inflater;
private List<DataSet> DataList;
ImageLoader imageLoader = Controller.getPermission().getImageLoader();

public Adapter(Activity activity, List<DataSet> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}

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

@Override
public Object getItem(int location) {
return DataList.get(location);
}

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

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

if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);

if (imageLoader == null)
imageLoader = Controller.getPermission().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView worth = (TextView) convertView.findViewById(R.id.worth);
TextView source = (TextView) convertView.findViewById(R.id.source);
TextView year = (TextView) convertView.findViewById(R.id.inYear);
DataSet m = DataList.get(position);
thumbNail.setImageUrl(m.getImage(), imageLoader);
name.setText(m.getName());
source.setText("Wealth Source: " + String.valueOf(m.getSource()));
worth.setText(String.valueOf(m.getWorth()));
year.setText(String.valueOf(m.getYear()));

return convertView;
}

}

  

Description of code:

  • In our GetView method, we are using ImageLoader’s object for checking if permission is granted or not.
  • We created an object of NetworkImageCiew which is basically Volley’s tool and TextView’s object, too.
  • Then we set all the data on different TextViews.

8.  Create Controller.java File.

  • This class controller our request and control our app.
package volleylistview.com.icoderslab.volleylistview;

import android.app.Application;
import android.text.TextUtils;

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


/**
* Created by Hatesh kumar on 11/07/2016.
*/

public class Controller extends Application {

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

private RequestQueue queue;
private ImageLoader ImageLoader;

private static Controller controller;

@Override
public void onCreate() {
super.onCreate();
controller = this;
}

public static synchronized Controller getPermission() {
return controller;
}

public RequestQueue getRequestQueue() {
if (queue == null) {
queue = Volley.newRequestQueue(getApplicationContext());
}

return queue;
}

public ImageLoader getImageLoader() {
getRequestQueue();
if (ImageLoader == null) {
ImageLoader = new ImageLoader(this.queue,
new BitmapCache());
}
return this.ImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}

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

public void cancelPendingRequests(Object tag) {
if (queue != null) {
queue.cancelAll(tag);
}
}

}

Description of code:

  • Here we created RequestQueue class object which is basically Volley’s main class ,I already gave the description of this class above.
  • Here we created ImageLoader class object which is basically Volley’s main class, I already gave the description of this class above.
  • Here we created Controller class instance.
  • We created method getRequestQueue() to get a request from the web server.

Finally.

9. Create BitmapCache.java File:

  • Now we are going to do the main coding for our application.
  • This file takes care of caching the image on disk.

v

package volleylistview.com.icoderslab.volleylistview;

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

import com.android.volley.toolbox.ImageLoader;


/**
 * Created by Hatesh kumar on 11/07/2016.
 */

public class BitmapCache extends LruCache<String, Bitmap> implements
        ImageLoader.ImageCache {

    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public BitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public BitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

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

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

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

Description of code:

  • We have created an instance of type BitmapCache and made the constructor to apply singleton pattern.
  • ImageCache is a cache adapter interface.

Running App:

  • Click on device manager. After selecting your custom (Emulator, Genymotion or mobile device) device manager window click NEXT.

Here is the output of your APP of Android Custom ListView Using Volley.

Android Custom ListView Using Volley
Download Code

BY HATESH KUMAR

One thought on “Android Custom ListView Tutorial Using Volley

  1. Thanks for the explanation. How do we make the listviews clickable, and display for example, the name and description of, say, Bill Gates, in another layout?

Leave a Reply

Your email address will not be published. Required fields are marked *