Dynamic Tablelayout in Android

Posted on Updated on

In this tutorial I am gonna to discuss about creating tablelayout dynamically during run-time. Dynamic tablelayout is useful while displaying data from a database or from a multiple list. The following are steps

  • Open eclipse and create a new Android project.
  • Create a database in our project (Only for tutorial purpose you can use the existing database in your project).
          try
             {
               database=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
               database.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL                                , NAME TEXT, LOCATION TEXT);");
               database.close();
            }
        catch(Exception e)
           {
               Log.e("Database Creation", "Error "+e.toString());
           }
  • Insert values into the database
        try
          {
              database=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
              database.execSQL("INSERT INTO " + TABLE + "(ID,NAME, LOCATION) VALUES(1,'ANTHONY','INDIA')");
              database.execSQL("INSERT INTO " + TABLE + "(ID,NAME, LOCATION) VALUES(2,'SHUING','USA')");
              database.execSQL("INSERT INTO " + TABLE + "(ID,NAME, LOCATION) VALUES(3,'JAMES','CHINA')");
              database.execSQL("INSERT INTO " + TABLE + "(ID,NAME, LOCATION) VALUES(4,'SOORYA','EUROPE')");
              database.execSQL("INSERT INTO " + TABLE + "(ID,NAME, LOCATION) VALUES(5,'MALIK','SRILANKA')");
              database.close();
           }
      catch(Exception e)
           {
               e.printStackTrace();
           }
  • Now in the main.xml add the following widgets
<?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" >
<ScrollView
 android:id="@+id/scrollView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
<LinearLayout
 android:id="@+id/linearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/tableLayout1"
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:stretchColumns="0,1" >
<TableRow
 android:id="@+id/tableRow1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" >
<TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="No."
 android:textAppearance="?android:attr/textAppearanceMedium" />
 <TextView
 android:id="@+id/textView2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="NAME"
 android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
 android:id="@+id/textView3"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="LOCATION"
 android:textAppearance="?android:attr/textAppearanceMedium" />
 </TableRow>
 </TableLayout>
 </LinearLayout>
 </ScrollView>
</LinearLayout>
  • Now in the display function initialize three TextViews and TableRow as follows
TableLayout tableLayout;
 TableRow row;
 TextView firstCol;
 TextView secondCol;
 TextView thirdCol;
database=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
 if(database!=null)
     {
          Cursor cursor=database.rawQuery("SELECT * FROM "+ TABLE, null);

            Integer index0=cursor.getColumnIndex("ID");
            Integer index1 = cursor.getColumnIndex("NAME"); 
            Integer index2 = cursor.getColumnIndex("LOCATION");
              if(cursor.getCount()>0)
                 {
                  cursor.moveToFirst();
                  do
                     {
                      row=new TableRow(this);
                      row.setId(100);
                      row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 

             /*Setting up the first coloumn parameters*/
              firstCol=new TextView(this);
              firstCol.setText(cursor.getString(index0));
              firstCol.setTextSize(16);
              firstCol.setTextColor(Color.GREEN);
              firstCol.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
              row.addView(firstCol); //adding coloumn to row
            /*Setting up the second coloumn parameters*/ 
              secondCol=new TextView(this);
              secondCol.setText(cursor.getString(index1));
              secondCol.setTextColor(Color.YELLOW);
              secondCol.setTextSize(16);
              secondCol.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
              row.addView(secondCol); //adding coloumn to row

            /*Setting up the third coloumn parameters*/
              thirdCol=new TextView(this);
              thirdCol.setText(cursor.getString(index2));
              thirdCol.setTextColor(Color.MAGENTA);
              thirdCol.setTextSize(16);
              thirdCol.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
              row.addView(thirdCol); //adding coloumn to row
            /*Adding the row to the tablelayout*/
              tableLayout.addView(row,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

          }while(cursor.moveToNext());
     database.close();
 }
 else
 {
             Toast.makeText(getBaseContext(), "NOT AVAILABLE", Toast.LENGTH_LONG).show();
 }
 }
  • Run the project. After successful execution the following will be the output

Click the following link to download the entire sample project

DOWNLOAD SAMPLE PROJECT

2 thoughts on “Dynamic Tablelayout in Android

    […] I discussed in my previous post creating Dynamic TableLayout in Android . Here an issue arises in Eclipse while using TableLayout with layoutParams. Eclipse will […]

    Deasy said:
    March 28, 2013 at 3:44 pm

    Thanks for the tutorial, I followed your direction, when i run the application, it did not display the result on my device, as i am testing with a real device.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s