In this post we will create an Android Custom GridView Example Application. In this android example we will get the images from server and will display in the grid. So we will be using.
- Web API to get the data and
- Volley library to fetch the data from Web API
After the completion our gridview will look like this.

So if you want to create the same then read the full post.
Creating an Android Custom GridView
Creating our Web API
The first thing needed for our Android Custom GridView project is a web api that would give us all the data to display in our GridView. Though I will not be covering the creating an API part. Below you can see the URL and this URL will give me the data for my Android Custom GridView.
http://www.simplifiedcoding.net/demos/SuperHeroes/superheroes.php
If you would go to the above given URL you will see the following JSON.
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 | [ { "image":"http://www.simplifiedcoding.net/demos/SuperHeroes/dhruva.jpg", "name":"Super Commando Dhruva" }, { "image":"http://www.simplifiedcoding.net/demos/SuperHeroes/parmanu.jpg", "name":"Parmanu" }, { "image":"http://www.simplifiedcoding.net/demos/SuperHeroes/nagraj.jpg", "name":"Nagraj" }, { "image":"http://www.simplifiedcoding.net/demos/SuperHeroes/doga.jpg", "name":"Doga" }, { "image":"http://www.simplifiedcoding.net/demos/SuperHeroes/tiranga.jpg", "name":"Tiranga" }, { "image":"http://www.simplifiedcoding.net/demos/SuperHeroes/bheriya.jpg", "name":"Bheriya" } ] |
This JSON would give data for our Android Custom GridView.
Now lets create a project in Android Studio for our Android Custom GridView.
Creating Android Custom GridView Project in Android Studio
- Open Android Studio and create a new Project. I created AndroidCustomGridView.
- As I told that I will be using Volley Library so first we need to add Volley Library to our Gradle Dependencies. So add volley inside the dependency block of your build.gradle file for app module.
1 2 3 4 5 6 7 8 9 10 | dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' //Volley Library - You need to add this line compile 'com.mcxiaoke.volley:library-aar:1.0.0' } |
- Our Android Custom GridView project need internet permission so go to the manifest file and add internet permission.
1 2 3 4 | <!-- INTERNET PERMISSION --> <uses-permission android:name="android.permission.INTERNET"/> |
- Now come to main layout file activity_main.xml of our Android Custom GridView app. Here we will create a GridView. Just use the below 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 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.androidcustomgridview.MainActivity"> <GridView android:id="@+id/gridView" android:layout_width="match_parent" android:layout_height="match_parent" android:columnWidth="90dp" android:gravity="center" android:horizontalSpacing="10dp" android:numColumns="3" android:stretchMode="columnWidth" android:verticalSpacing="10dp"></GridView> </LinearLayout> |
- Now come to MainActivity.java and declare the following variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class MainActivity extends AppCompatActivity { //Web api url public static final String DATA_URL = "http://www.simplifiedcodingreaders.16mb.com/superheroes.php"; //Tag values to read from json public static final String TAG_IMAGE_URL = "image"; public static final String TAG_NAME = "name"; //GridView Object private GridView gridView; //ArrayList for Storing image urls and titles private ArrayList<String> images; private ArrayList<String> names; |
- We need to initialize the GridView inside onCreate().
1 2 3 4 5 6 7 8 9 10 11 | @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = (GridView) findViewById(R.id.gridView); } |
- Now we will create a method to get the JSON Array from the API.
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 | private void getData(){ //Showing a progress dialog while our app fetches the data from url final ProgressDialog loading = ProgressDialog.show(this, "Please wait...","Fetching data...",false,false); //Creating a json array request to get the json from our api JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { //Dismissing the progressdialog on response loading.dismiss(); //Displaying our grid showGrid(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } ); //Creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //Adding our request to the queue requestQueue.add(jsonArrayRequest); } |
- Once we got the JSON Array as the response we are calling method showGrid() and passing the JSON Array. So We will create this method to display our grid. But before we need an Adapter that would create all the needed number of ImageViews to the Grid, and before creating the adapter 😛 we need to create a Custom Volley Request for our NetworkImageView.
- To display the images from the URL, I am going to use Volley’s NetworkImageView same as we did in many previous posts. So first create a class named CustomVolleyRequest.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 | package net.simplifiedcoding.androidcustomgridview; import android.content.Context; import android.graphics.Bitmap; import android.support.v4.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 Belal on 12/5/2015. */ public class CustomVolleyRequest { private static CustomVolleyRequest customVolleyRequest; private static Context context; private RequestQueue requestQueue; private ImageLoader imageLoader; private CustomVolleyRequest(Context context) { this.context = context; this.requestQueue = getRequestQueue(); 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 CustomVolleyRequest getInstance(Context context) { if (customVolleyRequest == null) { customVolleyRequest = new CustomVolleyRequest(context); } return customVolleyRequest; } public RequestQueue getRequestQueue() { 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; } } |
- Now lets create the Adapter for our GridView. Create a class named GridViewAdapter.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 | package net.simplifiedcoding.androidcustomgridview; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import java.util.ArrayList; /** * Created by Belal on 12/22/2015. */ public class GridViewAdapter extends BaseAdapter { //Imageloader to load images private ImageLoader imageLoader; //Context private Context context; //Array List that would contain the urls and the titles for the images private ArrayList<String> images; private ArrayList<String> names; public GridViewAdapter (Context context, ArrayList<String> images, ArrayList<String> names){ //Getting all the values this.context = context; this.images = images; this.names = names; } @Override public int getCount() { return images.size(); } @Override public Object getItem(int position) { return images.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { //Creating a linear layout LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); //NetworkImageView NetworkImageView networkImageView = new NetworkImageView(context); //Initializing ImageLoader imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader(); imageLoader.get(images.get(position), ImageLoader.getImageListener(networkImageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert)); //Setting the image url to load networkImageView.setImageUrl(images.get(position),imageLoader); //Creating a textview to show the title TextView textView = new TextView(context); textView.setText(names.get(position)); //Scaling the imageview networkImageView.setScaleType(ImageView.ScaleType.CENTER_CROP); networkImageView.setLayoutParams(new GridView.LayoutParams(200,200)); //Adding views to the layout linearLayout.addView(textView); linearLayout.addView(networkImageView); //Returnint the layout return linearLayout; } } |
- Now come back to MainActivity.java. We will now create the showGrid() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | private void showGrid(JSONArray jsonArray){ //Looping through all the elements of json array for(int i = 0; i<jsonArray.length(); i++){ //Creating a json object of the current index JSONObject obj = null; try { //getting json object from current index obj = jsonArray.getJSONObject(i); //getting image url and title from json object images.add(obj.getString(TAG_IMAGE_URL)); names.add(obj.getString(TAG_NAME)); } catch (JSONException e) { e.printStackTrace(); } } //Creating GridViewAdapter Object GridViewAdapter gridViewAdapter = new GridViewAdapter(this,images,names); //Adding adapter to gridview gridView.setAdapter(gridViewAdapter); } |
- Now at last just call the method getData() inside onCreate().
- So the final code for MainActivity.java would be.
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 | package net.simplifiedcoding.androidcustomgridview; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.GridView; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { //Web api url public static final String DATA_URL = "http://www.simplifiedcodingreaders.16mb.com/superheroes.php"; //Tag values to read from json public static final String TAG_IMAGE_URL = "image"; public static final String TAG_NAME = "name"; //GridView Object private GridView gridView; //ArrayList for Storing image urls and titles private ArrayList<String> images; private ArrayList<String> names; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = (GridView) findViewById(R.id.gridView); images = new ArrayList<>(); names = new ArrayList<>(); //Calling the getData method getData(); } private void getData(){ //Showing a progress dialog while our app fetches the data from url final ProgressDialog loading = ProgressDialog.show(this, "Please wait...","Fetching data...",false,false); //Creating a json array request to get the json from our api JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { //Dismissing the progressdialog on response loading.dismiss(); //Displaying our grid showGrid(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } ); //Creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //Adding our request to the queue requestQueue.add(jsonArrayRequest); } private void showGrid(JSONArray jsonArray){ //Looping through all the elements of json array for(int i = 0; i<jsonArray.length(); i++){ //Creating a json object of the current index JSONObject obj = null; try { //getting json object from current index obj = jsonArray.getJSONObject(i); //getting image url and title from json object images.add(obj.getString(TAG_IMAGE_URL)); names.add(obj.getString(TAG_NAME)); } catch (JSONException e) { e.printStackTrace(); } } //Creating GridViewAdapter Object GridViewAdapter gridViewAdapter = new GridViewAdapter(this,images,names); //Adding adapter to gridview gridView.setAdapter(gridViewAdapter); } } |
- Thats all for the coding part, now simply run your application now and you will see the following output.

- Bingo! our custom Android GridView is working absolutely fine. If you are getting any trouble you can get my code from GitHub via the link given below.
[wp_ad_camp_1]
Some More Android Tutorials You Should Check
Thats all for this android custom gridview tutorial. You can leave your comments for any feedback or query regarding this android custom gridview tutorial. And please support by sharing the tutorial to your social profiles. 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.
Great tutorial! thank Belal, Can you make a tutorial for Custom Recyclerview in Tab fragments?
Your welcome buddy.. just wait I will try to post the tutorial for your query ASAP.
Thanks Belal, You are truly the best! More knowledge and power to my great sir.
Hi, I have tried it.. but it is not fetching data.. Hope some problem with url..
Yeah as I gave the hosting details publically.. some one tried it for spamming and they blocked the hosting account 😛
You have to create your own web API to make it work
hello sir
this app cand start and show msg fetching dada thats
no resutl show and display in logcat
04-09 18:42:11.706 9483-9526/com.example.mk4.androidcustomgridview I/qtaguid: Tagging socket 42 with tag 3833279300000000(-1204607085) for uid -1 failed errno=-2
04-09 18:42:11.706 9483-9526/com.example.mk4.androidcustomgridview I/NetworkManagementSocketTagger: tagSocketFd(42, -1204607085, -1) failed with errno-2
I have corrected the url now try using this url
http://www.simplifiedcoding.16mb.com/superheroes.php
Hi Belal. The ProgressDialog won’t stop loading. Please help. Anyone successfully done this?
i also stuck in this problem ,who else can help , in hurry , need help .(T.T)
Maybe late reply, but I found a solution,
write this :
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage() + “.”, Toast.LENGTH_LONG).show();
}
instead of this :
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
Hey I got the same error, did you solve it? I would appreciate your help.
Thanks.
Would you send me the superheros.php for me to see because I can not fetch data make myself.
would you send the superheros.php because I can not fetch data when I create my own webAPI
Nice Tutorial …..Bilal can you make tutorial on Displaying data into the graph both locally and from online resource….thanks
would you write the gridview onclicklistener to view the full image?
would you write a tutorial that gridview onitemclicklistener to display the full image?
Thank you very much for this example because it has helped me a lot. I made the example, I am now trying a new activity, by an intent to show the image and name, I have not got, I keep trying. thank you.
I also create this activity too,would you help me??
Thank you very much for this example because it has helped me a lot. I made the example, I am now trying a new activity, by an intent to show the image and name, I have not got, I keep trying. thank you
Hey did you solve it? I’m trying to do the same thing but no luck. I would appreciate if you could help me.
Thanks!
Nice tutorial…. Can I download file superhero.php ??
Dude give the working code including android.
I am getting unfortunately stopped error.
How to add one more text under name in girdview ?
Hi!
Its my file superhero.php
If you are using the emulator then the file should be available http://10.0.2.2/api/superhero.php
I have it available as http://10.0.3.2/api/superhero.php
$row[5],
‘name’=>$row[1])
);
}
echo json_encode($result);
mysqli_close($con);
“gradle.builde ” where it locates in android eclipse. and how to it update!!!!!!!!!
Hi,
Am getting the error unfortunately app has been stopped,
and I gave this code for fragment
In getData()method , am getting the error
I have to use getActivity() or getContext() but am getting the same error for both of them
pls suggest me
I am also getting the same problem in fragments
Sorted out !!
you just define Context ctx in the mainActivity and use ctx in place of getActivity().
Hi, can i use it for making a grid view without the photo ?
If it yes, what I can remove from the code ?
Great tutorial Belal, I have followed this tutorial for my project.
But I have something in my mind.
Is there any code for the image shown in the grid view be able to be clicked and show the enlarge the picture?
Hi Bilal,
could you please help in how to delete images from gridView.
thanks
plzz help
how to add gridview onclicklistener ???
hello can u give me superhero.php file plz..
hello can u give me superhero.php file plz.. :'(
Hi Belal,
Can you please send superhero.php?
Please send this as soon as possible.
Thanks and regards,
Avinash Yadav
avinashsy143@gmail.com
can u make the next activity that show single_row when click on a particular click .Please i tried a lot but not getting the content on like Full description.class
can u please make single row activity of this file showing particular image
can you please send the superheros.php to my mail Dayadpr444@gmail.com
hi , do u receive the superheros.php file ?can u forward to me ? konan93_khang@hotmail.com
Thanks for the tutorial 🙂
Hey i am getting please wait fetching data and it is not loading anything can u help me?
can you ,please provide the php file for image and text parsing
Salam sir i need to know that how can i make my gridview responsive using volley , the grind view includes dynamic pictures and text i need to make them responsive those images to fit on screen perfectly those images are not from server i have stored them into drawables and i am picking them from there so yes i can not use networkimageview of volley
Thank you for the great app !
May I have the file (superhero.php) ?
Please…
windcjg@gmail.com
get ic_alert image 🙁
image not set in gridview only show aleart dialog. helm me 🙁
the url is not working..
hi belal , why dont u just upload the php code?
hello can u give me superhero.php file pls!!!!!!!!!!
hello I got this error in logcat
java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.util.ArrayList.size()’ on a null object reference
What could be the cause?
HI, Thank you for this nice tutorial. It helped me a lot. What if i want to send any post data with this request. How would i change the code ?
i facing same problem can you help me brother?
Hello it wont stop fetching data load progress.. and it doesn’t even display images can you help with the problem or can u plz send me superhero.php file..
may be because of url is not working
,”url”:”http:\/\/finalproject.16mb.com\/android\/uploads\/1.jpg”}
this is my image url get from database . i think that is because of my url so my app cannot fetch the img data .my url is difference with the top of the img url given . but i follow the previous tutorial
Hey could you solve this? I would appreciate your help!
Thanks.
Great tutorial! where can i add auth headers to the ImageLoader request?
can u give me ur php file? i stuck on the url step , i get the img url like this :
{“id”:”19″,”name”:”d1″,”url”:”http:\/\/www.finalproject.16mb.com\/android\/uploads\/19.jpg”}]}
dun know wat problem that cause my url to show like this.
1.replace $response[‘images’] with $response in php file
2.change ==> public static final String TAG_IMAGE_URL = “images”; to ====> “public static final String TAG_IMAGE_URL = “url” in your main class.
progress Dialogue wont stop.. Fetching Data… please help me…
http://dasassociates.org/paym/uploads/demop.php this is my php file running on server.. but i didnt get images & title from server
Thank you for your tutorial
Now I’m trying to make a application to view gridview of local image by voley, but when I try it always have java.lang.OutOfMemoryError exception, can you make a tutorial of this
type org.json.JSONObject cannot be converted to JSONArray
i m getting that error can anyone help me??
dialogbox is not stopped..it shows Fetching Data…
I tried your latest json too..but i get the same error.Would u Please help me
Debug the app n check whether u r getting value from server or not
Hi, I have an error, so I created a question on stackoverflow, can u reply?
http://stackoverflow.com/questions/16738279/android-org-json-jsonarray-cannot-be-converted-to-jsonobject
can we display .gif format in this application ?
Hi belal,
thanks for this tutorial
would you write a tutorial that gridview onitemclicklistener to display the full image?
appreciate for your help..
thanks…
Hey I want to do the same thing, did have any luck with this?
Thanks!
gridview onitemclicklistener to display the full image to share? please
how to set text below image in this gridview
In the end of GridViewAdapter you have to put this line –> linearLayout.addView(textView); below the second line linearLayout.addView(networkImageView);
like this:
//Adding views to the layout
linearLayout.addView(networkImageView);
linearLayout.addView(textView);
Hello Belal
Wonderful, It is a Great tutorial
it works perfectly. many thanks man
But i have a little problem with scrolling up, when I scroll down everything is fine, but when I scroll up from the end of the list, it’s not smooth and it jumps to end again and again. Did I miss anything here?
I’m looking forward for your answer
Hello Belal
How to change getview() to use an existing layout_grid_item.xml which contains textview and imageview
I hope you help me make this change
thanks
Hi
I want to use my predefined layout. In the above code the layout is created in run time but i want to use my predefined layout in xml file. how can use the code and my predefined layout.
Hello everyone, here problem is with php script
just follow this
1) make an array like this
$android = array();
now
$fetch_res = [‘image’=>’$image’,name=>’name’];
array_push($android,$fetch_res);
echo json_encode($android);
You will get Output like Belal’s json result
Thank You!!!
If image show dialog alert picture,
Add library compile ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’ in build.gradle
hello @Belal Khan really thank you your all tut and blogs are help full for all android developer.
i have use this Android-custom-gridview-images Code but i am some issue
actually i get same as JSON Data and also get totally path in my grid view but in my application text View is show Proper Name and Image is not showing …?
could u help me please .
Thank you.
Thank you
hello sir, i tried the above code with my own server i got the response array while running on postman chrome, but inside the android app Progressdialog is continuously loading, i am not getting the response at app end, even url is ok.
how to pass an argument in Volley GET request?
I have done successfully…!!!
Thanks bro.
Now i want to learn how fetch video from server in listview or recyclerview.
please make one example on it.
Thanks.
God bless you.