Json Array Object using GridView in Adnroid

Many of online store’s products list get from server using json array object. Nowadays every programming language having support for json format.
Now we are going to see how to create grid product view using json array object in android.

AndroidManifest.xml

Here android manifest xml file you should enable INTERNET permission for get product images from server.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.devsbucket.json_grid_sample">
    <uses-permission android:name="android.permission.INTERNET"
        tools:ignore="WrongManifestParent" />
    <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>

activity_main.xml

This what product archive page layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/products"
        android:clickable="true"
        android:numColumns="1" />
</android.support.constraint.ConstraintLayout>

grid_adapter.xml

In grid adapter xml file have single grid layout ( Single product how it will look declared here ).

   <?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:elevation="2dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:padding="15dp">
        <ImageView
            android:id="@+id/product_image"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".4"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".6"
            android:padding="5dp"
            android:orientation="vertical">
                <TextView
                    android:id="@+id/product_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:text="Nikon Camera"
                    android:textColor="#000"
                    android:textSize="20sp" />
                <TextView
                    android:id="@+id/product_amount"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="$ 350"
                    android:padding="5dp"
                    android:textColor="#037c05"
                    android:textSize="18sp" />
                <TextView
                    android:id="@+id/product_sml_description"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Frame rate selectable from 60p/50p/30p/25p/24p"
                    android:padding="5dp"
                    android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

MainActivity.java

This what the main java file for main activity

// Import java libraries 
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import org.json.JSONArray;

public class MainActivity extends AppCompatActivity {
    private Context context;
    private GridView gridView;
    private JSONArray SampleProducts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        gridView = (GridView) findViewById(R.id.products);
        renderSampleProduct();
        createGridView();
    }

    private void createGridView(){
        // Create grid adopter 
        GridAdapter productAdapter = new GridAdapter( this, SampleProducts );
        // Set grid adapter into GridView
        gridView.setAdapter( productAdapter );
    }

    private void renderSampleProduct(){
        // Sample data - you should get data from store sever same like format
        String sampleJsonString = "[{prod_name : \"Nikon D5300\", prod_thumb : \"https://cameradecision.com/img/px300_300/front_straight/Nikon-D5500.jpg\", prod_price : \"$460\", prod_desc : \"DSLR crafted to be lightweight yet full-on functionality, helping you revamp your photographic skills\"}, " +
                "{prod_name : \"Redmi Note 5\", prod_thumb : \"https://stat.homeshop18.com/homeshop18/images/productImages/385/micromax-spark-vdeo-q415-dual-sim-android-mobile-phone-gold-medium_6e3ae87ea6c41df8b74b798fcbc700ab.jpg\", prod_price : \"$120\", prod_desc : \"Stunning visuals on a 15.2 cm, 18:9 full-screen display with rounded corners\"}," +
                "{prod_name : \"IIK BLACK Watch\", prod_thumb : \"https://images.costco-static.com/ImageDelivery/imageService?profileId=12026539&imageId=1180670-894__1&recipeName=350\", prod_price : \"$50\", prod_desc : \"IIK COLLECTION BLACK for men\"}," +
                "{prod_name : \"V-neck Multicolor T-Shirt\", prod_thumb : \"https://3.imimg.com/data3/FG/CT/MY-8814506/polo-t-shirt-500x500.jpg\", prod_price : \"$20\", prod_desc : \"High quality cut & sew Designer V-Neck Tshirt direct from the manufacturers\"}]";
        try {
            SampleProducts = new JSONArray( sampleJsonString );
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

GridAdapter.java

For generate adapter view grid item


//Import java libraries
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;

public class GridAdapter extends BaseAdapter {
    private final Context Context;
    private final JSONArray productList;

    // Step 1
    public GridAdapter(Context context,JSONArray productList) {
        this.Context = context;
        this.productList = productList;
    }


    // Step 2
    @Override
    public int getCount() {
        return this.productList.length();
    }

    // Step 3
    @Override
    public long getItemId(int position) {
        return 0;
    }

    // Step 4
    @Override
    public JSONObject getItem(int position)  {
        JSONObject curJson = new JSONObject();
        try {
            curJson = this.productList.getJSONObject( position );
        } catch( Exception e ){
            e.printStackTrace();
        }
        return curJson;
    }

   // Step 5
    @Override
    public View getView(int position, View convertView, ViewGroup parent)  {
        LayoutInflater inflater = (LayoutInflater) Context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        // For single column
           View  gridView = inflater.inflate(R.layout.grid_adapter, null);
        // For double column
        // View  gridView = inflater.inflate(R.layout.grid_adapter_double_col, null);
        JSONObject SingleProduct = getItem(position);
        // Set adopter element into variable
        ImageView ProductImageView  = (ImageView) gridView.findViewById(R.id.product_image);
        TextView  ProductName       = (TextView) gridView.findViewById(R.id.product_name);
        TextView  ProductAmount     = (TextView) gridView.findViewById(R.id.product_amount);
        TextView  ProductSmlDesc    = (TextView) gridView.findViewById(R.id.product_sml_description);

        try {
            // Set into adabter imageview and textview
            new GetImageFromUrl(ProductImageView).execute(SingleProduct.getString("prod_thumb"));
            // ProductImageView.setImageDrawable(ContextCompat.getDrawable( Context, R.drawable.ic_camera_alt_black_24dp) );
            ProductName.setText( SingleProduct.getString("prod_name") );
            ProductAmount.setText( SingleProduct.getString("prod_price") );
            ProductSmlDesc.setText( SingleProduct.getString("prod_desc") );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return gridView;
    }
}


GetImageFromUrl.java

This class for get image in your web server using AsyncTask and set into ImageView

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.URL;

public class GetImageFromUrl extends AsyncTask<String,Void,Bitmap> {
    ImageView imageView;

    public GetImageFromUrl(ImageView imageView){
        this.imageView = imageView;
    }

    protected Bitmap doInBackground(String... url){
        String urlOfImage = url[0];
        Bitmap productImage = null;
        try{
            // Get image from server
            InputStream is = new URL(urlOfImage).openStream();
            productImage = BitmapFactory.decodeStream(is);

        } catch(Exception e){
            e.printStackTrace();
        }
        return productImage;
    }
    
    protected void onPostExecute(Bitmap result){
        // Set image into ImageView
        imageView.setImageBitmap(result);
    }
}


Android grid view result using json array object

If you want double column

    <?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:elevation="2dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:background="#fff"
        android:padding="15dp"
        android:orientation="vertical"
        android:layout_height="400dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight=".6"
            android:layout_height="0dp"
            android:background="#fff"
            android:padding="15dp"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/product_image"
                android:layout_width="180dp"
                android:layout_height="180dp"
                android:adjustViewBounds="true"
                android:scaleType="fitXY"
                android:layout_gravity="center"/>
        </LinearLayout>
        <LinearLayout
            android:layout_weight=".4"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:orientation="vertical"
            android:layout_gravity="center"
            android:textAlignment="center">
            <TextView
                android:id="@+id/product_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:text="Nikon Camera"
                android:textColor="#000"
                android:textSize="20sp"/>
            <TextView
                android:id="@+id/product_amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="$ 350"
                android:padding="2dp"
                android:textColor="#037c05"
                android:textSize="18sp"/>
            <TextView
                android:id="@+id/product_sml_description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Frame rate selectable from 60p/50p/30p/25p/24p"
                android:padding="2dp"
                android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

It should in GridAdapter.java line number 52 change into

View  gridView = inflater.inflate(R.layout.grid_adapter_double_col, null);

and also in activity_main.xml line number 12

android:numColumns="2"


Android grid view double column layout using json array object

Sample project - for android studio

About: Paranjothi

paranjothi@sarkware.com


One thought on “Json Array Object using GridView in Adnroid”

Leave a Reply

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