In this article I am going to explain how to display data in GridView in an Android application. Here is the example of Custom GridView in which I have used two TextViews.

  •     Start a new project named GridViewData.
  •     Open res/layout/main.xml and insert the following:
<?xml  version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"    
                android:id="@+id/gridview"   
                android:stretchMode="columnWidth"
                android:cacheColorHint="#00000000"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:numColumns="1"
                android:clipChildren="true"
                android:horizontalSpacing="5dip"
                android:verticalSpacing="5dip" />

·         Create a customgrid.xml inside res/layout folder and insert the following code:

<?xml  version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
<TableLayout android:id="@+id/TableLayout01"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent">
       <TableRow android:id="@+id/TableRow01"
                  android:layout_height="wrap_content"
                  android:layout_width="wrap_content">
        <TextView  android:text="@string/hello"
            android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                   android:id="@+id/txtId"
                  android:layout_gravity="center_horizontal" />
        
        <TextView  android:text="@string/hello"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:id="@+id/txtName"
                  android:layout_gravity="center_horizontal" />
       </TableRow>
</TableLayout>
</LinearLayout>
  •    Create DataAdapter.java file and insert the following code: 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
 
public class DataAdapter extends BaseAdapter
{
       Context mContext;
       private String [] id = {"S001","S002","S003","S004","S005","S006","S007"};
       private String [] name={"Rohit","Rahul","Ravi","Amit","Arun","Anil","Kashif"};
       private LayoutInflater mInflater;
       public DataAdapter(Context c)
       {
              mContext=c;
              mInflater = LayoutInflater.from(c);
       }
       public int getCount()
       {
              return id.length;
       }
       public Object getItem(int position)
       {
              return position;
       }
       public long getItemId(int position)
       {
              return position;
       }
       public View getView(int position, View convertView, ViewGroup parent)
       {
              ViewHolder holder=null;
              if(convertView==null)
              {
                     convertView = mInflater.inflate(R.layout.customgrid,
                                                                    parent,
                                                                    parent,false);
                     holder = new ViewHolder();
                     holder.txtId=(TextView)convertView.findViewById(R.id.txtId);
                     holder.txtId.setPadding(100, 10,10 , 10);
                     holder.txtName=(TextView)convertView.findViewById(R.id.txtName);
                     holder.txtName.setPadding(100, 10, 10, 10);
                     if(position==0)
                     {                             
                           convertView.setTag(holder);
                     }
              }
              else
              {
                     holder = (ViewHolder) convertView.getTag();
              }
              holder.txtId.setText(id[position]);
              holder.txtName.setText(name[position]);
              return convertView;
       }
       static class ViewHolder
       {        
              TextView txtId;        
              TextView txtName;               
       }
}

·         Open the main activity file and modify according to it:

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
 
public class GridViewDataActivity extends Activity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridview = (GridView) findViewById(R.id.gridview);  
       gridview.setAdapter(new DataAdapter(this));
    }
}

  •       Run the application.

The output should look like below:

The output should look like below:

Display Data in GridView in Android


  Modified On Nov-30-2017 06:26:01 AM
  1. Hi firzan gulam,

    The basic PHP datagrid requires only two lines of code. Fore mostly, always create PHPGrid object in the first line; then call its methods to define properties, and lastly always call display() to render to screen.

    Code:
    $phpDataGrid = new C_DataGrid("Select * from MySQLTable", "PrimaryKeyOfTable", "TableName");
    $phpDataGrid-> display();

    I hope it might be useful for you.

  1. hi
    I am trying to retrieve data from MySQL and display in grid view... but i only get success in retrieve the data from MySQL.... but yet not got success to display in data grid view... so, please help me... i want to display data from MySQL to android in data grid format.. my project stop because of it.. so please send me whole source code of it..
    please reply me... it's very urgent...

    thank you..
  1. hi
    Sirinivas

    report.java

    package sale.com;
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.ListActivity;
    import android.net.ParseException;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.Toast;
    public class SaleReport extends ListActivity {
       
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            String result = null;
            InputStream is = null;
            StringBuilder sb = null;
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            List<String> r = new ArrayList<String>();
           
            try{
            //http post
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("give_path of ur server/php file name like(record.php)");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            }
            catch(Exception e){
                Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
           }
           
            //Convert response to string 
            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
               
                sb = new StringBuilder();
               
                String line = null;
               
                while ((line = reader.readLine()) != null)
                {
                   sb.append(line + "\n");
                }
               
                is.close();
               
                result = sb.toString();
            }
            catch(Exception e)
            {
                Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
            }
            //END Convert response to string  
            try{
                    JSONArray jArray = new JSONArray(result);
                    JSONObject json_data=null;
                    for(int i=0;i<jArray.length();i++)
                    {
                       json_data = jArray.getJSONObject(i);
                       r.add(json_data.getString("plant"));
                       r.add(json_data.getString("date"));
                       r.add(json_data.getString("time"));
                       r.add(json_data.getString("saledate"));
                       r.add(json_data.getString("salesinmts"));
                  
                   }
                   setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
                }
                catch(JSONException e1){
                    Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
                } catch (ParseException e1) {
                    Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
              }
               
        }
    }
    record.php

    <?php
    $username="root";
        $password="";
        $database="collection";
        $local="localhost";
    $con = mysql_connect("$local","$username","$password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db($database, $con);
    $result = mysql_query("SELECT plant,date,time,saledate.salesinmts FROM sale WHERE plant ='Pune' );
    while($row = mysql_fetch_array($result))
      $output[]=$row;
        print(json_encode($output));
       
    ?>

    In manifest file add one line

    <uses-permission android:name="android.permission.INTERNET">


  1. Hi
    Rohit used static data and simply display in grid view,

    {
      private String [] id = {"S001","S002","S003","S004","S005","S006","S007"};
      private String [] name={"Rohit","Rahul","Ravi","Amit","Arun","Anil","Kashif"};
    }

    but i want to access it from MySQL and display in grid view... Simply Server Client connection.... retrieve data from database and display in grid view format on emulator.....

    if u see the code which i have paste for srinivas in that i used MySQL databse from where i retrieve the data and simply display on emulator like that only i want to display it in grid view...

    Please as soon as possible send m source code for it...
     
  1. The Vertical scrolling of gridview gives force close error.

Leave Comment