Android gridview example

If you want create an image gallery or product list or any type of list that you want to display in grid format then android gridview layout is used to such type of need. Android gridView is a very flexible, Powerful and highly customisable component. You could create views like Image gallery with text and description or product list with image, title, price, description and buy now button etc.
In order to used this Android GridView layout component we need to create 5 files in our android app.

1. Activity – In which we will show our GridView layout.
2. Activty layout xml file.
3. Adapter class – To fill data in grid
4. layout of adapter class – Layout file responsible for rendering column in gridview. We can customize design of each column in this layout file.
5. Record Class – This file holds record. it is a combination of data and function so we can set/get values from a row of record.

Lets start the coding of Android gridview component. Lets assume we need to show a product list in a gridview format and have following fields in our product list.

1. id
2. product_name
3. prod_desc
4. product_image

Open an empty activity ProductActivity and its layout file.

In its layout file whose name should be activity_product.xml. put below code in this file.

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="110dp"
android:drawSelectorOnTop="false"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"
/>

Now we need to fetch json data from api to fill in the gridview component. before it we need to create other dependent files to avoid errors.

Create a new file called Product.java and put this code in this file.

public class Product implements Serializable {
private String id;
private String product_name;
private String prod_desc;
private String product_image;

public Product(String id, String product_name, String prod_desc, String product_image) {
super();
this.id = id;
this.product_name = product_name;
this.prod_desc = prod_desc;
this.product_image = product_image;
}

public String getID() {
return id;
}

public void setID(String id) {
this.id = id;
}

public String getName() {
return product_name;
}

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

public String getProdDesc() {
return prod_desc;
}

public void setProdDesc(String prod_desc) {
this.prod_desc = prod_desc;
}

public String getImage() {
return product_image1;
}

public void setImage(String product_image) {

this.product_image = product_image;
}

}

Now create a new file ProductViewAdapter.java and put below code in this file.


public class ProductViewAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList<Product> data = new ArrayList();

public ProductViewAdapter(Context context, int layoutResourceId, ArrayList data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;

if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.prod_id = (TextView) row.findViewById(R.id.prod_id);
holder.product_name = (TextView) row.findViewById(R.id.product_name);
holder.prod_desc = (ImageView) row.findViewById(R.id.prod_desc);
holder.product_image = (TextView) row.findViewById(R.id.product_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}

//int loader = R.drawable.loader;
// Imageview to show

Product Productitem = data.get(position);

holder.prod_id.setText(Productitem.getID());

holder.product_name.setText(Productitem.getName());

holder.prod_desc.setText(Productitem.getProdDesc());

String image_url = Productitem.getImage();

Picasso.with(this.context)
.load(image_url)
.into(holder.product_image1);

return row;
}

static class ViewHolder {
TextView prod_id;
TextView product_name;
TextView prod_desc;
ImageView product_image;

}
}

We can put as many fields as we want in a single column of a gridview component and we can customize its design as we want. Each column of gridview required a single layout file.
lets a create new layout file named product_item_layout.xml and put this code in this file.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:orientation="vertical"
android:padding="5dp"
android:paddingTop="20dp">

<ImageView
android:id="@+id/product_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1dp"
android:adjustViewBounds="true"

/>

<TextView
android:id="@+id/product_name"
android:layout_width="match_parent"
android:textAllCaps="false"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textAlignment="center"
android:gravity="center"
android:textSize="@dimen/content_size"
android:textColor="@color/contentColor"
/>

<TextView
android:id="@+id/prod_desc"
android:layout_width="match_parent"
android:textAllCaps="false"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textAlignment="center"
android:gravity="center"
/>

<!-- we keep the product id invisible, this if for reference only -->
<TextView
android:id="@+id/prod_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:gravity="center"
android:textSize="0dp"
android:visibility="invisible" />

</LinearLayout>

Now its time to fetch json data from the api and render its data in the grid view component. Open your activity class and put below code in your ProductActivity.java.


public class ProductActivity extends AppCompatActivity {

Intent intent;
RequestQueue queue;

Activity activity;
Context context;

GridView gridView;

private Toolbar mToolbar;

ProductViewAdapter gridAdapter;
public ArrayList<Product> products = new ArrayList<>();

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

activity = this;

context = getApplicationContext();

String url = "http://www.example.com/getjsondata.php";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);

JSONObject results = jsonObject.getJSONObject("results");
JSONArray data = results.getJSONArray("data");

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

JSONObject jo = data.getJSONObject(i);
String id = jo.getString("id");
String product_name = jo.getString("product_name");
String product_image = jo.getString("product_image");
String prod_desc = jo.getString("prod_desc");
products.add(new Product(id, product_name, prod_desc, product_image))
}
} catch (JSONException e) {
e.printStackTrace();
}

GridView gridView = (GridView) findViewById(R.id.gridView);

gridAdapter = new ProductViewAdapter(ProductActivity.this, R.layout.product_item_layout, products);

gridView.setAdapter(gridAdapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

//write code to execute on tab on a single column of gridview
}
});

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Api Error", "Api Not working " + error);
}
});

stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue = Volley.newRequestQueue(getApplicationContext());
queue.add(stringRequest);

}
}

The json parsing code used in the activity class is written to parse this type of Json. You can modify json parsing code according to you api response.


{
"results": {
"status": 200,
"msg": "OK",
"data": [
{
"id": 1,
"product_name": "product name goes here",
"prod_desc": "product description goes here",
"product_image": "http://www.example.com/images/product_image1.jpg",
},
{
"id": 2,
"product_name": "product name goes here",
"prod_desc": "product description goes here",
"product_image": "http://www.example.com/images/product_image2.jpg",
},

]
}
}

We have used volley for fetch api data and picasso to render image in imageview. you can include volley and picasso by including this code in app.gradle in dependencies section.

compile ‘com.squareup.picasso:picasso:2.4.0’
compile ‘com.android.volley:volley:1.0.0

in the next article i will show you how you can implement paging in this gridview component.

Leave a Reply

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

eleven + eighteen =