Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    APIs
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> Android >> Display Data in GridView in Android
Display Data in GridView in Android
Display Data in GridView in Android


by Rohit Kesharwani on 11/1/2011 1:28:24 PM

Views: 15578       Comments: 14

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

Report Abuse Form
Reason:    
 


retrieve the data from mysql and display in Grid View
by firzan gulam 12/2/2011 12:14:36 AM
thanks for post ...

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

kindly reply

 thanks ... 
Report Abuse

Retrieve the data from MySQL and display in GridView
by Arun Singh 12/15/2011 5:52:30 AM

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.

Report Abuse

Retrieve the data from MySQL and display in GridView in android
by Aishwarya Taware 1/31/2012 11:17:26 PM
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..
Report Abuse

Retrieve the data from MySQL and display in GridView in android
by Rohit Kesharwani 2/1/2012 12:33:41 AM
Hi,

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

Thanks.
Report Abuse

Retrieve the data from MySQL and display in GridView in android
by Aishwarya Taware 2/3/2012 2:57:25 AM
hi
u still haven't send me the source code of my query.
Please send it...

Thank you
 
Report Abuse

Retrieve the data from MySQL and display in GridView in android
by Haider M Rizvi 2/3/2012 3:33:46 AM

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

Report Abuse

Retrieve the data from MySQL and display in listview android
by srinivas padala 2/16/2012 3:34:05 AM

   

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

Report Abuse

Retrieve the data from MySQL and display in listview android
by srinivas padala 2/16/2012 4:16:03 AM

 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

Report Abuse

Retrieve the data from MySQL and display in listview android
by firzan gulam 2/17/2012 11:25:10 PM
check this link

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

Retrieve the data from MySQL and display in listview android
by Aishwarya Taware 2/20/2012 2:26:53 AM
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..
Report Abuse

Retrieve the data from MySQL and display in listview android
by Aishwarya Taware 2/20/2012 2:38:18 AM
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>
Report Abuse

Retrieve the data from MySQL and display in listview android
by Haider M Rizvi 2/20/2012 5:39:16 AM

Hi Ashwarya,

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

Report Abuse

Retrieve the data from MySQL and display in listview android
by Aishwarya Taware 3/21/2012 6:09:39 AM
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...
 
Report Abuse

hi
by Nive P 6/22/2012 11:54:50 PM
The Vertical scrolling of gridview gives force close error.
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Rohit KesharwaniRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 7281
Advertisement
MindStick Cleaner
Advertise with Us
  
Copyright © 2009 - 2013MindStick. All Rights Reserved.