Home > DeveloperSection > Beginner > Display Data in GridView in Android

Display Data in GridView in Android


Android Android 
Ratings:
14 Comment(s)
 50500  View(s)
Rate this:

Display Data in GridView in Android


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,
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:

Display Data in GridView in Android


retrieve the data from mysql and display in Grid View

By firzan gulam on   5 years ago
thanks for post ...

now plz tell me how i display the retried data from mysql (using php) to the grid view...

kindly reply

 thanks ... 

Retrieve the data from MySQL and display in GridView

By Arun Singh on   4 years ago

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.


Retrieve the data from MySQL and display in GridView in android

By Aishwarya Taware on   4 years ago
hi

im 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..

Retrieve the data from MySQL and display in GridView in android

By Rohit Kesharwani on   4 years ago
Hi,

Please paste your code here, how you are retrieving data from MySQL and display in grid view.

Thanks.

Retrieve the data from MySQL and display in GridView in android

By Aishwarya Taware on   4 years ago
hi
u still haven't send me the source code of my query.
Please send it...

Thank you
 

Retrieve the data from MySQL and display in GridView in android

By Haider M Rizvi on   4 years ago

Hi Aishwarya,

Could you please paste your code here so that we can easily find the issue in your code and you get solved asap.

Thanks


Retrieve the data from MySQL and display in listview android

By srinivas padala on   4 years ago

   

asiwarya thaware

 

hai sister, i search for retreving mysql data into android app from 1 week, but i failed to found it, plz plz... can give your code .. urgent . its very helpful for my final year project


Retrieve the data from MySQL and display in listview android

By srinivas padala on   4 years ago

 i search for                     retreving mysql data into android app                   from 1 week, but i failed to found it, plz plz... can

give your code .. urgent . its very helpful for my final year project   .. plz plz post me full source code including php files ..

 

or to my mailid--- srinivaspadala.cs@gmail.com


Retrieve the data from MySQL and display in listview android

By firzan gulam on   4 years ago
check this link

http://firzan786.blogspot.com/2012/02/retrieve-data-from-mysql-and-display-in.html

Retrieve the data from MySQL and display in listview android

By Aishwarya Taware on   4 years ago
hi
Haider M Rizvi,

            I  used  Rohit Kesharwani code. so plz can you send m source code which will help m to retrieve data
from MySQL server and display in Grid View.

Thank You..

Retrieve the data from MySQL and display in listview android

By Aishwarya Taware on   4 years ago
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"></uses-permission>

Retrieve the data from MySQL and display in listview android

By Haider M Rizvi on   4 years ago

Hi Ashwarya,

Can you please explain about the problem you are getting in implementing the above given code of Rohit?


Retrieve the data from MySQL and display in listview android

By Aishwarya Taware on   4 years ago
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...
 

hi

By Nive P on   4 years ago
The Vertical scrolling of gridview gives force close error.

Don't want to miss updates? Please click the below button!

Follow MindStick