Android ListView → Android Simple ListView – Fill with List of Objects – Camposha

Android ListView

Android ListView

Android ListView

Android Simple ListView – Fill with List of Objects


How to populate a simple ListView with a java List of POJOs.

In this tutorial we see how to fill a simple listview with “Person” objects.When clicked we show the Person’s name in a Toast message.

===

Concepts You will Learn from this Example

  1. What is a ListView?
  2. What is a List Collection?
  3. How to populate a ListView from a List of POJO Objects data structure in android studio.
  4. How to simple click listener in a listview.
  5. What is an ArrayAdapter?
  6. How to use ArrayAdapter to bind a java list to a simple listview.

How to Define ListView in XML Layout

You use the ListView object as the element:

    <ListView
        android_id="@+id/lv"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
         />

How To Reference a ListView in Java Code

Here’s how you reference a ListView. You use the findViewById() method:

ListView lv= (ListView) findViewById(R.id.lv);

(a). Initializing a Java List

Here’s how you can initialize a List. You cannot directly instantiate since as we said it’s an interface:

    List<String> people=new ArrayList<>();

(b). How to Clear a Java List

You can remove all items in a java list using the clear() method:

    people.clear();

(c). Populating a Java List with Objects

You can populate a java list using the add() method:

    private void fillPeople()
    {
        Person p=new Person();
        p.setName("Mike");
        people.add(p.getName());

        p=new Person();
        p.setName("John");
        people.add(p.getName());
        .....

Read more about java list here.

What is an ArrayAdapter?

We need an adapter to work with a listview.

An adapter is a class that acts as a bridge between an adapterview and the underlying data source.

In this case we’ll use an ArrayAdapter.

You can read more about ArrayAdapter here.

1. Project Demo

Here’s the demo of the example:

Project Demo

2. Android Studio and Project Ceation

(a). What is Android Studio?

We will use Android Studio, the official IDE for android development. Android Studio is maintained by both Google and Jetbrains.

Android Studio comes bundled with the Android SDK Manager, which is a tool that allows us download the Android SDK components required to develop android applications.

To learn more about Android Studio go here.

(b). How to Create an Empty Activity in Android Studio
  1. First create an empty project in android studio. Go to File –> New Project.
  2. Type the application name and choose the company name.
  3. Choose minimum SDK.
  4. Choose Empty activity.
  5. Click Finish.

This will generate for us a project with the following:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity View.You add your views and widgets here.
2. MainActivity.java Class Our Launcher activity

To learn more about how to create an android project in android studio go here.

(c). Generated Project Structure in Android Stduo

Android Studio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

2. Resources.

Android platform provides a powerful and flexible way of adding static content as a resource.

These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.

Resources belong to a given type. These types can be:

  1. Drawable.
  2. Layout.
  3. Value.

Let’s start by looking at the layout resources

(a). activity_main.xml

This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    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.listviewandobjects.MainActivity">

    <ListView
        android_id="@+id/lv"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
         />
</RelativeLayout>

3. Java Code.

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Java programming language.

We will have these classes in our project.

(a). Person.java

This is our data object. This class will represent a single person.

A single person will have these properties:

  1. id – an Integer. The id of the person.
  2. name – The name of the person. A String.

Then our list will comprise Person objects.

package com.tutorials.hp.listviewandobjects;

public class Person {

    int id;
    String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

This is our launcher activity as the name suggests. This means it will be the main entry point to our app in that when the user clicks the icon for our app, this activity will get rendered first.

We override a method called onCreate(). Here we will start by inflating our main layout via the setContentView() method.

Our main activity is actually an activity since it’s deriving from the AppCompatActivity.

package com.tutorials.hp.listviewandobjects;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List<String> people=new ArrayList<>();

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

        //LISTVIEW
        ListView lv= (ListView) findViewById(R.id.lv);

        //FILL LIST
        fillPeople();

        //ADAPTER
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,people);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, people.get(i), Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void fillPeople()
    {
        people.clear();
        Person p=new Person();
        p.setName("Mike");
        people.add(p.getName());

        p=new Person();
        p.setName("John");
        people.add(p.getName());

        p=new Person();
        p.setName("Lucy");
        people.add(p.getName());

        p=new Person();
        p.setName("Rebecca");
        people.add(p.getName());

        p=new Person();
        p.setName("Kris");
        people.add(p.getName());

        p=new Person();
        p.setName("Kurt");
        people.add(p.getName());

        p=new Person();
        p.setName("Vin");
        people.add(p.getName());
    }
}

4. Download

Everything is in the source code reference. It is well commented and easy to understand and can be downloaded below.

Also check our video tutorial it’s more detailed and explained in step by step.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Our YouTube Channel

Leave a Reply

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

X