Show data in columns in a TableView dynamically in Android.

By | December 26, 2011

Hello all,
Often we need to show data from a source such as a database in a tableView like we see in an HTML Page. In Android also we can do this with the help of TableLayout. We can create dynamic rows and add data to it.

Android Dynamic Table UI

MainActivity

package table_demo.coderzheaven.com.tabledemo;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    String companies[] = {"Google", "Windows", "iPhone", "Nokia", "Samsung",
            "Google", "Windows", "iPhone", "Nokia", "Samsung",
            "Google", "Windows", "iPhone", "Nokia", "Samsung"};
    String os[] = {"Android", "Mango", "iOS", "Symbian", "Bada",
            "Android", "Mango", "iOS", "Symbian", "Bada",
            "Android", "Mango", "iOS", "Symbian", "Bada"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addHeaders();
        addData();
    }

    private TextView getTextView(int id, String title, int color, int typeface, int bgColor) {
        TextView tv = new TextView(this);
        tv.setId(id);
        tv.setText(title.toUpperCase());
        tv.setTextColor(color);
        tv.setPadding(40, 40, 40, 40);
        tv.setTypeface(Typeface.DEFAULT, typeface);
        tv.setBackgroundColor(bgColor);
        tv.setLayoutParams(getLayoutParams());
        tv.setOnClickListener(this);
        return tv;
    }

    @NonNull
    private LayoutParams getLayoutParams() {
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(2, 0, 0, 2);
        return params;
    }

    @NonNull
    private TableLayout.LayoutParams getTblLayoutParams() {
        return new TableLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
    }

    /**
     * This function add the headers to the table
     **/
    public void addHeaders() {
        TableLayout tl = findViewById(R.id.table);
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(getLayoutParams());
        tr.addView(getTextView(0, "COMPANY", Color.WHITE, Typeface.BOLD, Color.BLUE));
        tr.addView(getTextView(0, "OS", Color.WHITE, Typeface.BOLD, Color.BLUE));
        tl.addView(tr, getTblLayoutParams());
    }

    /**
     * This function add the data to the table
     **/
    public void addData() {
        int numCompanies = companies.length;
        TableLayout tl = findViewById(R.id.table);
        for (int i = 0; i < numCompanies; i++) {
            TableRow tr = new TableRow(this);
            tr.setLayoutParams(getLayoutParams());
            tr.addView(getTextView(i + 1, companies[i], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));
            tr.addView(getTextView(i + numCompanies, os[i], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));
            tl.addView(tr, getTblLayoutParams());
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        TextView tv = findViewById(id);
        if (null != tv) {
            Log.i("onClick", "Clicked on row :: " + id);
            Toast.makeText(this, "Clicked on row :: " + id + ", Text :: " + tv.getText(), Toast.LENGTH_SHORT).show();
        }
    }
}

Layout

Below is the layout that actually holds the table in the layout.

Here is the activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
    android:scrollbars="none"
    tools:context="table_demo.coderzheaven.com.tabledemo.MainActivity">

    <TableLayout
        android:id="@+id/table"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="0,1" />

</ScrollView>

Source code

You can download the complete source code from here.

20 thoughts on “Show data in columns in a TableView dynamically in Android.

  1. trugur

    Thanks a lot. I did this. However i want to get selected row values in the table. For example when i touched second row in above screen i want to get “Windows” and “Mango” values. How can i do this?

    Reply
    1. James Post author

      @trugur:- Add a click eventListener to the textView and onClick get the view.getText(). that’s all.

      Reply
      1. trugur

        I tried but i couldn’t find gettext function. Can you give me a simple example?
        And this is what i have tried:

        tr.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        v.setBackgroundColor(Color.DKGRAY);
        v.showContextMenu();

        }
        });

        Reply
        1. James Post author

          Don’t add listener for table row, instead add listener for the textview inside it. set it the id as same as the row number. So when you click on it, you will get the text in it and the row number which is it’s id.

          Reply
          1. trugur

            Thank you for your help.
            I added listener for textview. But now it gives me text of last row. I think i coudn’t do about id. I’m not so good about this subject. Could you give me simple example please? I’ll be glad.

    1. James Post author

      Did you check your php code is error free?
      if it is ok, try to print the response from the server in the Logcat.

      Reply
  2. Flexicious

    Fully Customizable Rows and Columns with Support for Inline Filters, Summary Footers, Server/Client Paging, Sort, Excel/Word Export, Locked Columns, Inline Edit, User Settings Persistence and a lot more!

    Reply
  3. Farrukh

    i am doing same but screen show nothing, help plzzzzzzzzzzz

    Reply
  4. Farrukh

    also heaving error in “setContentView(R.layout.main);” as cannot resolve symbol ‘main’
    plzzzzz help

    Reply
    1. James Post author

      Farrukh,

      This is because there is some error in the XML file. Please fix it and this error will go away.

      Reply
  5. Shubho Sikder

    I used this code for dynamic table column. But my table data is being inverse. like data row is being column and column is being row.

    My edition code is…
    public void addData() {
    TableLayout tl = findViewById(R.id.table);

    for(int i = 0; i < columnNames.length; i++) {
    array = null;
    ar = null;
    ar = new ArrayList();
    c.moveToFirst();
    do {
    ar.add(c.getString(c.getColumnIndex(""+columnNames[i]+"")));
    }while (c.moveToNext());
    array = new String[ar.size()];
    array = ar.toArray(array);
    int length = array.length , l = 0;
    TableRow tr = new TableRow(this);
    tr.setLayoutParams(getLayoutParams());
    for (int j = 0; j < array.length; j++) {
    tr.addView(getTextView( j + 1, array[j], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));

    }
    tl.addView(tr, getTblLayoutParams());

    }

    Reply

Leave a Reply

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