Android ArrayAdapter - ListView and ArrayList

android arrayadapter java arraylist

Adapters like ArrayAdapter help bridge the gap between model data and the adapterview,two very different parts of a List application with different responsibilities.

Our model data represents our data source.It maybe from a database or a simple data collection,like say array or arraylist.

The adapterview represents the visual representations.AdapterViews are concerned with showing data.Adapterviews include ListViews,GridViews and spinner.

Our adapter shall help link these two. ArrayAdapters work with an array or java.util.List instance. It takes :

  1. Context.
  2. Resource ID of the view to be used in the adapterview.
  3. List of data to be bound.

What we do :

  • Fill our adapterview with data.
  • Our adapterview in this case is be a simple ListView.
  • We use ArrayAdapter as our adapter.
  • Our data source is an arraylist.
  • So we instantiate and set to our listview using the setAdapter() method.
  • While instantiating our adapter we need to pass a context,layout and data source.
  • We handle our itemclicks and show a simple toast message.

What You do :

  • Create a project in android studio.
  • Give it a name and choose minimum and target SDKs.

Create Project

  1. First create an empty project in android studio. Go to File --> New Project.

  2. Type the application name and choose the company name. New Project Dialog
  3. Choose minimum SDK. Choose minimum SDK
  4. Choose Empty activity. Choose Empty Activity
  5. Click Finish. Finish

This will generate for us a project with the following:

  • 1 Activity - MainActivity.java
  • 1 Layout - activity_main.xml.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component. If you've created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

SECTION 1 : Our Dependencies

Build.Gradle
  • Android Studio has added for us dependencies for AppCompat and Design support libraries.
  • Note we are subclassing AppCompatActivity to make our MainActivity class an activity.

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

SECTION 2 : Our Activity

Our MainActivity

Main Responsibility : LAUNCH OUR APP.

  • It extends AppcompatActivity hence is an activity.
  • Activities are the entry point of android applications.This is no exception.
  • It loads our activity layout.
  • Our activity layout has our ListView.
  • We therefore reference that ListView and set its adapter.
  • We first instantiate our arrayadapter,passing in context,layout and data source.
  • Our arrayadapter is of generic type string.
  • To set our adapter to listview we use the setAdapter() method.
  • Our data source is a simple arraylist.
    package com.tutorials.hp.listviewarraylist;

    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;

    public class MainActivity extends AppCompatActivity {

        ArrayList<String> numbers=new ArrayList<>();
        ListView lv;

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

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

            //FILL DATA
            fillData();

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

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

        //FILL DATA
        private void fillData()
        {
            for (int i=0;i<10;i++)
            {
                numbers.add("Number "+String.valueOf(i));
            }
        }
    }

SECTION 3 : Our Layouts

ActivityMain.xml Layout.

This layout will get Inflated as our activity's view. This happens via the setContentView() method.

Whatever we add to this layout shall therefore represent part of our activity's hierarchy.

In this case we add a simple ListView. ListView display items in vertical list.

We need to assign the ListView an ID as we will reference from the MainActivity class.

At the root we have a RelativeLayout which is a container layout.

    <?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.listviewarraylist.MainActivity">

        <ListView
            android:id="@+id/lv"
            android:layout_width="match_parent"
            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

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post