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.
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 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
how to construct json object in php
cerrection:
TextView textViewName = (TextView)listViewItem.findViewById(R.id.textViewName);
TextView textViewImageUrl = (TextView)listViewItem.findViewById(R.id.textViewImageUrl);
You don’t need to typecast here.. 🙂 Try without typecasting it will work .. Anyways thank you
Without Type cast it gives error, like Error:(41, 59) error: incompatible types: View cannot be converted to TextView
You are using an older SDK, update your android studio and SDK and you do not need to typecast
it is showing error without typecasting
hey am getting an error in my php scripts which is telling me this:
br />
Fatal error: Call to a member function prepare() on null in
C:\xampp\htdocs\android1\include\DbOperations.php on line
62
can u help me plz?
In this case make sure the SQL query is correct. To confirm the query is correct open your phpmyadmin and try executing the query you written on the code, and confirm it is working fine or not.
Hi Belal! Thanks for this tutorial. I would like to ask that, how do i able to display IF the data is empty in the database and it will show “Data is Empty” in a fragment or a dialog box ELSE it will straight display the data IF the database table are inserted a data. Thank you!
when i start the app then it will show recent search from json then i have to clear the cache of the app then it with show the latest search so please help me that it will refresh every time app with start.
Thank you belal. I am seeing this type of tutorial for some days but not find good but not i found this thanks.
Also when i change my php code and add some more details then it will not show. then i have to clear data of app and then it will refresh so plz tell me about this problem that ho can i fix it.
belal bhai please reply about this question fast. please
You can set the volley cache to false using
request.setShouldCache(false);
May be this is the problem in your case.
How to make toast on listview on clicking in this tutorial.
I have no volly library dependency in my android studio 2.3.3, what to do?? As during adding dependency and syncing error occurred.
I need a help sir.
I have an access token along with GetCategory.
Can you share or demonstrate how to deal with it ?
Can you tell how to implement searchview for the above code?
How to fetch the json data and store it locally before populating the list.
my app crashes when I click on the link provided on listview. How do i solve it.
how to get json data when we change the url …
How to hide a JSON_URL string, after decompiling the APK through tool URLs are easily shown, please tell me a proper solution
instead of hiding add some authentication to your urls, so that without proper auth no one can send requests.
What if we want to send array to php?
For example
//java
params.put(“s1”,max[0]);
params.put(“s1”,max[1]);
….
params.put(“s1”,max[n]);
//php
$s1_result = $_POST[“s1”];
My problem is I can’t able to use key s1 morethan once in java (map)
So is there any other way to do this ?
How to store the json data to view it offline when Internet is not availaible?
Wonderful tutorial… I have been using AsyncTask but this is ok for my need right now.
can you send or upload the php script?
Hi ,
I am using oauth protocol and need to implement the refresh token policy onvolley. I have written the part where I send a request , generate a token and raise requests using that token but I would love a tutorial on complex parts of volley like how to set retry poilcy if a request fails
Thankyou So Much..It was Wonderful..!
How to hide json file to browser view becuase any one can use our site json show how to protect….jt from browser view can you explain this
Check this video tutorial and you will understand: https://goo.gl/e3j18R
I also recommends watching whole series.
when i login the app the user_id is going in database but when we don’t login the app then user_id is not go in databse.how i send the user_id in backend database in every situation using volley in android.
hello sir
I have one problem please solve ,when i click in image url so screen force close ,why create this problem
I’m facing the same issue. Plz help!!
Excellent work ! i was searching for this code… you made my day
sir m getting timeout error while reading data as a response so it coming under
on ErrorResponse()
what to do sir?
Hello Belal Khan, Thanks for this tutorial of android volley.
Can you show us for this tuto the php script please?? Because I don’t see that value name of array “heroes”.
And if possible build some tutorial of retrieving data mysql by using or entry “id” like $id=$_POST[‘id’] . PLEASE … HELP ME
Everything is already covered here check -> https://www.simplifiedcoding.net/android-networking-tutorial/
i m getting same data from every GET request if i insert new data JsonObjectRequest only fech old records not new inserted records
Sir, can I get example on displaying one web service on different activies in android? Means displaying json objects on different activies through comparing id’s between them.