Hey guys, welcome to Simplified Coding. This post is about Android Volley Tutorial. And here we will do a straightforward thing. I have a URL that gives me some JSON data, and by using Volley I will get that data, and I will also parse it. So if you want to learn how do we fetch and parse JSON from a URL in android then let’s start this Android Volley Tutorial.
Table of Contents
Note: This tutorial covers only sending an http get request to a URL using Volley if you want to learn about all the http requests you can watch this playlist.Â
What is Android Volley?
Now if you are a newbie then you might be thinking that what the hell is Volley :P. So the answer for this question is “Volley is an HTTP Library  that makes networking for our apps easier and faster”.
Why Android Volley?
Volley simplify the networking task in android and with volley it is
- Easy to use request management
- Efficient network management
- Easily customizable according to our need
Android Volley Tutorial
Now lets begin the main task, the android volley tutorial. So as I told you at starting I have a URL that contains some JSON data. So below you can see my URL.
1 2 3 |
https://simplifiedcoding.net/demos/view-flipper/heroes.php |
You can use the same URL for your project. If you open the above URL, you will see the following. (Here I am using postman so that we can see pretty JSON structure but the browser will also show the same thing without formatting).
Now you can see we have some JSON data. At first, we have a JSON object, then inside that object, we have a key name heroes that contain an array of JSON objects. Each object in the array has two more keys name and imageurl. So our task here is to fetch this data and display it into a ListView.
But before moving ahead, if you think you should learn JSON first, then here is a seven minute quick video to learn everything about JSON.
Creating a new Android Studio Project
- As always the first step is creating a new Project. So here I am creating a project named MarvelHeroes. Now name doesn’t matter at all you can create your project with any name you want. Just remember you have to select an Empty Activity while creating the project.
- Once your project is loaded we will define internet permission on the manifest as we are going to perform a network operation and it requires internet permission.
Adding Internet Permission
- Open the AndroidManifest.xml file and add internet permission as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedlearning.marvelheroes"> <!-- adding internet permission --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
Adding Volley Library
- This is the important step 😛 (LOL). As we are going to use volley it is obvious that we have to add volley to our project. Don’t worry adding volley is quite easy.
- Just open your app level build.gradle file. If you are confused what it is then see the screenshot below.
- Inside this file you need to add volley library inside dependencies block, as show below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' //adding volley library compile 'com.android.volley:volley:1.0.0' testCompile 'junit:junit:4.12' } |
- Now sync your project and you are done with adding volley library.
Data Model Class
- To store the fetched data in objects we will create a simple model class. So create a class named Hero.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package net.simplifiedlearning.marvelheroes; /** * Created by Belal on 9/5/2017. */ public class Hero { String name, imageUrl; public Hero(String name, String imageUrl) { this.name = name; this.imageUrl = imageUrl; } public String getName() { return name; } public String getImageUrl() { return imageUrl; } } |
- The above class will be only used to hold the json data that we will fetch. That is why the class is having only a constructor to initialize the fields and getters to get the values.
Creating a ListView
- As I told you already that we will display the fetched data in a ListView. And here we are going to create a custom ListView.
- So first inside activity_main.xml create a ListView. In the below code you see we have a ProgressBar as well. This is because when the data is getting fetched we will show it so that user can get that something is loading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedlearning.marvelheroes.MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> |
- Now we need a layout for our list items.
Custom Layout for List Items
- Inside the layout directory (res->layout)Â create a new layout resource file named list_items.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical"> <TextView android:id="@+id/textViewName" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewImageUrl" android:layout_width="match_parent" android:layout_height="wrap_content" android:autoLink="web" android:textColor="#08308e" /> </LinearLayout> |
- As we have two items (name and imageurl) in our json data, we created to TextViews here to display the fetched data here.
Creating Custom Adapter
- As we are creating a custom ListView so we need to create a custom ArrayAdapter for our ListView.
- For this create a new class named ListViewAdapter.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package net.simplifiedlearning.marvelheroes; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; /** * Created by Belal on 9/5/2017. */ public class ListViewAdapter extends ArrayAdapter<Hero> { //the hero list that will be displayed private List<Hero> heroList; //the context object private Context mCtx; //here we are getting the herolist and context //so while creating the object of this adapter class we need to give herolist and context public ListViewAdapter(List<Hero> heroList, Context mCtx) { super(mCtx, R.layout.list_items, heroList); this.heroList = heroList; this.mCtx = mCtx; } //this method will return the list item @Override public View getView(int position, View convertView, ViewGroup parent) { //getting the layoutinflater LayoutInflater inflater = LayoutInflater.from(mCtx); //creating a view with our xml layout View listViewItem = inflater.inflate(R.layout.list_items, null, true); //getting text views TextView textViewName = listViewItem.findViewById(R.id.textViewName); TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewImageUrl); //Getting the hero for the specified position Hero hero = heroList.get(position); //setting hero values to textviews textViewName.setText(hero.getName()); textViewImageUrl.setText(hero.getImageUrl()); //returning the listitem return listViewItem; } } |
- Now the last part is fetching and parsing the json and displaying it to the ListView.
Fetching and Parsing JSON using Volley
- Now come inside MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
package net.simplifiedlearning.marvelheroes; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { //the URL having the json data private static final String JSON_URL = "https://simplifiedcoding.net/demos/view-flipper/heroes.php"; //listview object ListView listView; //the hero list where we will store all the hero objects after parsing json List<Hero> heroList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initializing listview and hero list listView = (ListView) findViewById(R.id.listView); heroList = new ArrayList<>(); //this method will fetch and parse the data loadHeroList(); } private void loadHeroList() { //getting the progressbar final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar); //making the progressbar visible progressBar.setVisibility(View.VISIBLE); //creating a string request to send request to the url StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { //hiding the progressbar after completion progressBar.setVisibility(View.INVISIBLE); try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); //we have the array named hero inside the object //so here we are getting that json array JSONArray heroArray = obj.getJSONArray("heroes"); //now looping through all the elements of the json array for (int i = 0; i < heroArray.length(); i++) { //getting the json object of the particular index inside the array JSONObject heroObject = heroArray.getJSONObject(i); //creating a hero object and giving them the values from json object Hero hero = new Hero(heroObject.getString("name"), heroObject.getString("imageurl")); //adding the hero to herolist heroList.add(hero); } //creating custom adapter object ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext()); //adding the adapter to listview listView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); //creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //adding the string request to request queue requestQueue.add(stringRequest); } } |
- Now run the application.
- Bingo! It is working absolutely fine.
Android Volley Tutorial – Fetching JSON Source Code
- Even after following each step carefully, you are having some troubles then here is my source code for you. Remember it is always your fault not the computers, and sometimes we think that we did the right thing, but it was our fault. So here is my tested source code for this Android Volley Tutorial.
[sociallocker id=1372] Android Volley Tutorial – Fetching JSON Source Code[/sociallocker]
So that’s all for this Android Volley Tutorial friends. If you have any confusions or queries feel free to leave your comments.
And if you found this post helpful, then please SHARE this with your friends and tell others about Simplified Coding. Thank You 🙂