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]
[sociallocker id=1372] Android Custom GridView Example [/sociallocker]
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 🙂