Monday, August 10, 2015

How to add items to ListView programmatically in Android

Add Item To ListView Programmatically
ListView is an Android element that allows users to select an item from a simple list. ListView displays a vertical list of items where an item is positioned immediately below another item/view. ListView items are vertically scrollable. ListView shows multiple items at a time. Android app users can vertically scroll ListView to see more items.

ListView items are populated from an array adapter. And this array adapter is also generated from an array of elements. ListView setAdapter method binds the array adapter with the ListView widget.

Sometimes android app developers want to add items to the ListView control after data bind with the array adapter. This call dynamically adds the items to the ListView control or programmatically adds items to the ListView element.

This android app development tutorial, show you how can we add items to the ListView element programmatically on the Button click event.

In the first step, we will add items to the ArrayList on the Button click event. Next, we will notify the array adapter about the change we made on its array list. Array adapter builds by array list and ListView items are populated from the array adapter.

So, when we add items to the array list it will directly add to the ListView element and when we notify the array adapter about the addition it will update the ListView and users are see the newly added items on the ListView widget. ArrayAdapter notifyDataSetChanged method allows us to inform the array adapter of any kind of change we made in the array list.
MainActivity.java

package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        Button button = findViewById(R.id.button);
        ListView listView = findViewById(R.id.listView);


        // Initializing a new String Array
        String[] fruits = new String[] {
                "Cape Gooseberry",
                "Capuli cherry"
        };

        // Create a List from String Array elements
        final List<String> fruits_list = new ArrayList<String>
                (Arrays.asList(fruits));

        // Create an ArrayAdapter from List
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
                (
                        this,
                        android.R.layout.simple_list_item_1,
                        fruits_list
                );


        // DataBind ListView with items from ArrayAdapter
        listView.setAdapter(arrayAdapter);


        // Set the button click listener
        button.setOnClickListener(view -> {
            // Add new Items to List
            fruits_list.add("Loquat");
            fruits_list.add("Pear");

            // Notify the adapter about the data change
            arrayAdapter.notifyDataSetChanged();

            // Disable the button itself
            view.setEnabled(false);
        });
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add New Items To ListView"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>