Android TableView - Fill With List of Objects - With Headers and RowClick


Android has a couple of inbuilt adapterviews like ListView,GridView,RecyclerView and Spinner that are used as the core of most modern apps.And thats pretty good cause most apps consist of Lists of data.The above generally display lists of data.

However,there are situations where you want to use the old fashioned table,with rows and columns.Infact in desktop and web development,with programming languages like Java and C# the tableviews are the most popular.Think components like JTable and DataGridView.

Today we use TableView library by Codecrafters and craft a table with header,rows and columns.Moreover,we handle ItemClicks,showing a toast message.

Project Demo

We are Building a Vibrant YouTube Community

We have a fast rising YouTube Channel of friends. So far we've accumulated almost 3 million agreggate views and more than 10,000 subscribers as of the time of writing this. Here's the Channel: ProgrammingWizards TV.

Please go ahead subscribe(free obviously) as well. If you have a question or a comment you can post there instead of in this site.People are suggesting us tutorials to do there so you can too.

Before we get into our example, we need to introduce the few classes that we will be using.

What is TableView?

TableView is an android library that allows us create and work with Tables in android.

It contains a simple TableView and an advanced SortableTableView.

There is both a free and a premium version of tableView.

Requirements of a TableView

TableView requires Android Minimum SDK version of 11 and Compule SDK Version of 25.

Installing TableView

TableView can be installed by adding the following implementation statement in your app leve build.gradle:

implementation 'de.codecrafters.tableview:tableview:2.8.0'

Working with TableView

This involves two processes:

  1. Addding the TableView Element in Your Layout:
<de.codecrafters.tableview.TableView
    xmlns:table="http://schemas.android.com/apk/res-auto"
    android:id="@+id/tableView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    table:tableView_columnCount="4" />

You can modify the number of columns you want your android table to have.

  1. Referencing the TableView: Then you reference the TableView in your Java code:
    TableView tableView = (TableView) findViewById(R.id.tableView);

    Here you can also modify the number of columns you want:

    tableView.setColumnCount(4);

Handling Column Widths

TableView allows you modify the column widths in various manners:

  1. Absolutely Using TableColumnDpWidthModel or TableColumnPxWidthModel Here's an example with TableColumnDpWidthModel:

    TableColumnDpWidthModel columnModel = new TableColumnDpWidthModel(context, 4, 200);
    columnModel.setColumnWidth(1, 300);
    columnModel.setColumnWidth(2, 250);
    tableView.setColumnModel(columnModel);

    And here's one with TableColumnPxWidthModel:

    TableColumnPxWidthModel columnModel = new TableColumnPxWidthModel(4, 350);
    columnModel.setColumnWidth(1, 500);
    columnModel.setColumnWidth(2, 600);
    tableView.setColumnModel(columnModel);
  2. Relatively with the TableColumnWeightModel The defauly column weight is 1.
    TableColumnWeightModel columnModel = new TableColumnWeightModel(4);
    columnModel.setColumnWeight(1, 2);
    columnModel.setColumnWeight(2, 2);
    tableView.setColumnModel(columnModel);

Showing Data

Data can be shown easily in TableView with help of SimpleTableDataAdapter class.

This allows us easily render two-dimensional string array in a tabular format.

This adapter will turn the strings you supply into TextViews and display them inside TableView at the same position as previous in the 2D-String-Array.

Here's an example:

public class MainActivity extends AppCompatActivity {

    private static final String[][] SPACESHIPS = { "Casini", "Chemical", "NASA", "Jupiter" }, 
                                                     { "Spitzer", "Nuclear", "NASA", "Alpha Centauri" } };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TableView<String[]> tableView = (TableView<String[]>) findViewById(R.id.tableView);
        tableView.setDataAdapter(new SimpleTableDataAdapter(this, SPACESHIPS));
    }
} 

Let's look at a full example.

What we do :

  • Show a tableview.
  • Populate its column headers with data.The header has its own adapter using SimpleTableHeaderAdapter.
  • Populate rows with data .It has its own adapter using SimpleTableDataAdapter.
  • Change header background color and set its column count.
  • Handle ItemClicks for our rows.
  • When a row is clicked show a toast with clicked data.

SECTION 1 : Our Dependencies

Build.Gradle

  • Android Studio has added for us dependencies for AppCompat library for our AppCompatActivity.
  • Now lets add dependencies for TableView.
  • It shall be fetched from online so be connected fro the first time you are adding.

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.tutorials.hp.tablelistobjects"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'de.codecrafters.tableview:tableview:2.2.0'
}

   

SECTION 2 : Our Data Object

Spacecraft.java

  • Represents a single object.Here I'll use Spacecraft.
  • The object shall have various properties like name,title,date etc.
  • Each object shall occupy a specific row.
  • Its corresponding properties then occupy the cells.

 

package com.tutorials.hp.tablelistobjects;

public class Spaceprobe {

    String id,name,propellant,destination;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPropellant() {
        return propellant;
    }

    public void setPropellant(String propellant) {
        this.propellant = propellant;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }
}

     

SECTION 3 : Our Activity

MainActivity class.

Main Responsibility : LAUNCH OUR APP.

  • We shall reference the views like TableView  here,from our XML Layouts.
  • We then initialize our SimpleTableHeaderAdapter and SimpleTableDataAdapters.
  • Then pass our data aray to it.
  • Header shall take a single dimensional array while the data shall take a multidimensional array.
  • Then set them to our tableview.
  • Then hande our itemclicks.

 

package com.tutorials.hp.tablelistobjects;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import java.util.ArrayList;

import de.codecrafters.tableview.TableView;
import de.codecrafters.tableview.listeners.TableDataClickListener;
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
import de.codecrafters.tableview.toolkit.SimpleTableHeaderAdapter;

public class MainActivity extends AppCompatActivity {

    String[] spaceProbeHeaders={"ID","Name","Propellant","Destination"};
    String[][] spaceProbes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TableView<String[]> tb = (TableView<String[]>) findViewById(R.id.tableView);
        tb.setColumnCount(4);
        tb.setHeaderBackgroundColor(Color.parseColor("#2ecc71"));

        //POPULATE
        populateData();

         //ADAPTERS
        tb.setHeaderAdapter(new SimpleTableHeaderAdapter(this,spaceProbeHeaders));
        tb.setDataAdapter(new SimpleTableDataAdapter(this, spaceProbes));

        tb.addDataClickListener(new TableDataClickListener() {
            @Override
            public void onDataClicked(int rowIndex, Object clickedData) {
                Toast.makeText(MainActivity.this, ((String[])clickedData)[1], Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void populateData()
    {
        Spaceprobe spaceprobe=new Spaceprobe();
        ArrayList<Spaceprobe> spaceprobeList=new ArrayList<>();

        spaceprobe.setId("1");
        spaceprobe.setName("Pioneer");
        spaceprobe.setPropellant("Solar");
        spaceprobe.setDestination("Venus");
        spaceprobeList.add(spaceprobe);

        spaceprobe=new Spaceprobe();
        spaceprobe.setId("2");
        spaceprobe.setName("Casini");
        spaceprobe.setPropellant("Nuclear");
        spaceprobe.setDestination("Jupiter");
        spaceprobeList.add(spaceprobe);

        spaceprobe=new Spaceprobe();
        spaceprobe.setId("3");
        spaceprobe.setName("Apollo");
        spaceprobe.setPropellant("Chemical");
        spaceprobe.setDestination("Moon");
        spaceprobeList.add(spaceprobe);

        spaceprobe=new Spaceprobe();
        spaceprobe.setId("4");
        spaceprobe.setName("Enterpise");
        spaceprobe.setPropellant("Anti-Matter");
        spaceprobe.setDestination("Andromeda");
        spaceprobeList.add(spaceprobe);

        spaceProbes= new String[spaceprobeList.size()][4];
        // spaceProbes= new String[][]{{}};

        for (int i=0;i<spaceprobeList.size();i++) {

            Spaceprobe s=spaceprobeList.get(i);

            spaceProbes[i][0]=s.getId();
            spaceProbes[i][1]=s.getName();
            spaceProbes[i][2]=s.getPropellant();
            spaceProbes[i][3]=s.getDestination();

        }
    }

}

   

SECTION 5 : Our Layouts

ActivityMain.xml Layout.

  • Inflated as our activity's view.
  • Includes our content main.
  • In this case shall hold our tableview.So please add the below tableview tag with its appropriate properties.

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorials.hp.tablelistobjects.MainActivity">

    <de.codecrafters.tableview.TableView
        android:id="@+id/tableView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</RelativeLayout>

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post