Will Will - 1 month ago 9
Android Question

Populating a table with an array of data

I want to set up a table which has a fixed amount of columns, and an X amount of rows with The first row listing the contents of each column. For example, one column will be 'Name' and a second column will be 'Age', then there will be an X amount of rows which store the data. Is there any way that I can set up arrays for this data elsewhere, and automatically create/fill the rows of the table with this data. I've done this previously with a more simple example using a Custom Adapter but I'm not quite sure how to go about this with a table involved. I'm quite stuck and any help would be greatly appreciated.

Answer

A ListView basically acts as a row within any table of data. You should create a POJO with all the attributes you want to display in a row. You can create create a custom xml layout for the data, which would probably by a horizontal LinearLayout that corresponds to your columns.

POJO

public class MyData {
    public String Name;
    public int Age;
    // More data here
}

ListView item layout (layout_list_item.xml)

<?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="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/Name"
            android:layout_height="wrap_content"
            android:layout_width="0dip"
            android:layout_weight="0.7" />

        <TextView
            android:id="@+id/Age"
            android:layout_height="wrap_content"
            android:layout_width="0dip"
            android:layout_weight="0.3" />

    </LinearLayout>

Main Layout

<?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">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="0dip"
                android:layout_weight="0.7"
                android:text="Name" />

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="0dip"
                android:layout_weight="0.3"
                android:text="Age" />

        </LinearLayout>

        <ListView
            android:id="+@id/MyDataListView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

     </LinearLayout>

You then need a custom adapter which sets the fields in the list view with the values from your POJO. There are plenty of tutorials on the internet for this.