How to use dynamic TableLayout instead of using ListView in Android.

Using ListView for showing data in vertical rows format is always good option but things become difficult when you want to use any widgets in rows of ListView.Although it can be done by using CustomAdapter but when you want to perform action on those widgets (like checking CheckBox or etc.) things become terrifying.For implementig this you need to maintain state of each widget and that part is the difficult one.
For simplicity there is one more way by creating dynamic TableLayout.Although it is complex to implement but once you become familier with it ,it becomes simple.
Here in this example I am creating a dynamic TableLayout whose each row contains a TextView and a Button.Button’s behaviour is made like CheckBox.So on clicking button you can make it check or uncheck.
The advantage of this over using dynamic ListView is you don’t need to worry about saving state of each widget.You can make it easy as any other widget which is static rather than created dynamically.

The XML code is simple.

And in the Java Code .
I have used three special variable

1.) final int CHECK_BUTTON_ID; :– This variable is used for creating ids of dynamically created button (or you can say CheckBox);
2.) int ids_check[]; :– This integer array is array of ids of each Button which is dynamically created in TableRow.
3.) boolean bool_check[]; :– This boolean array is used for keeping knowledge of each Button which is checked or unchecked.

and a very important method createTableRows() :– This method creates the TableRows and all these rows are added to TableLayout.
In this method I have used TableRow,TextView & Button variables whose properties are set by there respective methods.You can customize these by way you want.

*The most important thing in using this way of creating dynamic TableLayout import this android.widget.TableRow.LayoutParams
instead of android.view.ViewGroup.LayoutParams

This is a simple example of dynamic TableLayout with only two widgets you can use as many as you want. It seems to be quit complex but once you done with it you can use with very ease.

package com.ab1209.table.dynamic;

import java.util.ArrayList;
import android.R.bool;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class DynamicTable extends Activity
{
TableLayout table;

ArrayList list_name;

int color_blue = -16776961;
int color_gray = -7829368;
int color_black = -16777216;
int color_white = -1;

final int CHECK_BUTTON_ID = 982301;
int ids_check[];
boolean bool_check[];

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout) findViewById(R.id.tableLayout1);

list_name = new ArrayList();

list_name.add(“Close”);
list_name.add(“Cristiano”);
list_name.add(“David”);
list_name.add(“Fernando”);
list_name.add(“Messi”);
list_name.add(“Kaka'”);
list_name.add(“Wayne”);

bool_check = new boolean[list_name.size()];
ids_check = new int[list_name.size()];
createTableRows();

}

public void createTableRows()
{
for (int i = 0; i < list_name.size(); i++)
{
TableRow table_row = new TableRow(this);
TextView tv_name = new TextView(this);
Button btn_check = new Button(this);
ImageView img_line = new ImageView(this);

table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
table_row.setBackgroundColor(color_white);
table_row.setGravity(Gravity.CENTER_HORIZONTAL);

tv_name.setText(list_name.get(i));
tv_name.setTextColor(color_blue);
tv_name.setTextSize(16);
tv_name.setTypeface(Typeface.DEFAULT_BOLD);
tv_name.setWidth(150);

btn_check.setLayoutParams(new LayoutParams(30, 30));
btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);

img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
img_line.setBackgroundResource(R.drawable.separater_line);

table_row.addView(tv_name);
table_row.addView(btn_check);

table.addView(table_row);
table.addView(img_line);

int id = i + CHECK_BUTTON_ID;
btn_check.setId(id);
ids_check[i] = id;

btn_check.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
for (int j = 0; j < ids_check.length; j++)
{
Button btn_check_1 = (Button) findViewById(ids_check[j]);
if(v.getId() == ids_check[j])
if(bool_check[j])
{
btn_check_1.setBackgroundResource(R.drawable.small_checkbox_unchecked);
bool_check[j] = false;
}
else
{
btn_check_1.setBackgroundResource(R.drawable.small_checkbox_checked);
bool_check[j] = true;
}
}
}
});

}
}
}

About these ads

21 thoughts on “How to use dynamic TableLayout instead of using ListView in Android.

  1. hi to your code when i try to add radio group with radio buttons it is showing errors . in my xml layout i have tablelayout under scroll view and error is 2-10 11:40:24.120: E/AndroidRuntime(995): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pace.damnit/com.pace.damnit.DamnitActivity}: java.lang.NullPointerException

    public class DamnitActivity extends Activity {
    TableLayout makeit;
    ArrayList list_name;
    int color_blue = -16776961;
    int color_gray = -7829368;
    int color_black = -16777216;
    int color_white = -1;

    final int CHECK_BUTTON_ID = 982301;
    int ids_check[];
    boolean bool_check[];
    String[] values = new String[] { “Android”, “iPhone”, “Windows”,
    “Black”, “WebOS”, “Ubuntu”, “Windows7″, “MaxOSX”,
    “Linux”, “OS/2″ };
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, values));
    makeit = (TableLayout) findViewById(R.id.tableLayout1);
    list_name = new ArrayList();

    list_name.add(“Close”);
    list_name.add(“Cristiano”);
    list_name.add(“David”);
    list_name.add(“Fernando”);
    list_name.add(“Messi”);
    list_name.add(“Kaka”);
    list_name.add(“Wayne”);
    list_name.add(“ghse”);
    list_name.add(“gouse”);
    list_name.add(“ghuse”);
    list_name.add(“ghous”);
    list_name.add(“ouse”);
    list_name.add(“use”);
    list_name.add(“e”);
    list_name.add(“eff”);
    list_name.add(“euyr”);
    list_name.add(“ejjyytuty”);
    list_name.add(“madre”);
    list_name.add(“yuir”);
    list_name.add(“eyrty”);
    list_name.add(“etytr”);
    list_name.add(“ewrrtt”);
    bool_check = new boolean[list_name.size()];
    ids_check = new int[list_name.size()];
    createTableRows();

    }

    public void onListItemClick(ListView parent, View v, int position, long id){

    }

    public void createTableRows()
    {
    for (int i = 0; i < list_name.size(); i++)
    {

    TextView tv_name = new TextView(this);
    Button btn_check = new Button(this);
    ImageView img_line = new ImageView(this);
    RadioGroup mgroup=new RadioGroup(this);
    RadioButton newRadioButton = new RadioButton(this);
    newRadioButton.setText("hi");

    LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
    RadioGroup.LayoutParams.WRAP_CONTENT,
    RadioGroup.LayoutParams.WRAP_CONTENT);
    mgroup.addView(newRadioButton, 0, layoutParams);

    tv_name.setText((CharSequence) list_name.get(i));
    tv_name.setTextColor(color_blue);
    tv_name.setTextSize(30);
    tv_name.setTypeface(Typeface.DEFAULT_BOLD);
    tv_name.setWidth(150);

    btn_check.setLayoutParams(new LayoutParams(30, 30));
    btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);

    img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
    img_line.setBackgroundResource(R.drawable.separater_line);

    makeit.addView(tv_name);
    makeit.addView(btn_check);
    makeit.addView(mgroup);

    int id = i + CHECK_BUTTON_ID;
    btn_check.setId(id);
    ids_check[i] = id;

    btn_check.setOnClickListener(new OnClickListener()
    {
    @Override
    public void onClick(View v)
    {
    // TODO Auto-generated method stub
    for (int j = 0; j < ids_check.length; j++)
    {
    Button btn_check_1 = (Button) findViewById(ids_check[j]);
    if(v.getId() == ids_check[j])
    if(bool_check[j])
    {
    btn_check_1.setBackgroundResource(R.drawable.small_checkbox_unchecked);
    bool_check[j] = false;
    }
    else
    {
    btn_check_1.setBackgroundResource(R.drawable.small_checkbox_checked);
    bool_check[j] = true;
    }
    }
    }
    });

    }
    }
    }

    • Hi ghouse,

      I don’t think there should be any problem in adding a RadioButton to a dynamic TableLayout.
      It shall work fine.
      And regarding exception you are getting check your other code or Manifest file.

      Thanks

  2. hi,
    i am adding table row with textview ,radiogroup and imageview and i want them in this order textview imageview
    radio group how can i do that
    thanks for the replay.

    • Hello ghouse,
      I am very glad that you are using this concept.
      For adding views to TableRow in particular order you can add (by addView(View) method) in same sequence like in your case first add TextView then ImageView and last RadidGroup.Alternatively you can use addView(view, index) method where index is position where you want to add your view.
      Hope this will be helpful for you.

      Thanks

      • Hi,
        i am able to add three views but i want to display them in vertical manner and right now it is adding in a horizontal manner and i have also tried addView(view,index ) but it is displaying in same manner this is the code .
        table_row.addView(tv_name ,0);

        table_row.addView(iu,1);
        table_row.addView(mRadioGroup,2);
        and hope is this the way you were telling to me?

    • Hi ghouse,
      For solving of your problem you can use any of two ways

      First: Instead of adding view to a table_row just add your views(TextView,ImageView and RadioGroup)
      directly to table.

      for eg instead of
      table_row.addView(tv_name ,0);

      table_row.addView(iu,1);
      table_row.addView(mRadioGroup,2);
      just add to table like

      table.addView(tv_name);
      table.addView(iu);
      table.addView(mRadioGroup);

      Second approach :
      You can create a LinearLayout variable and set its orientation to Vertical and add your views to this layout and at the end add this layout to your table_row or directly to table.

      I hope it helps
      Thanks

  3. HI,
    i have another doubt that i want to save the data and store in a server in that case shall i save using sqlite or shall i use xml ?if i go for sqlite is it possible for me to directly save the sqlite database on the server.

    Thanks for you precious advice and time.

    • Hi ghouse,

      SQLite databases on android are private to the device. You can not choose their location either. They will always be stored in a directory under /data/data on your device. You can, however, copy it between locations.

      Also, as SQLite is a “serverless” database, there’s now way of using any “remote database”.

      Thanks

      • Hi,
        sorry i didn’t get your point .you mean to say that sqlite placed in the assest folder can’t be transferd on to the server using post method?

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