Android ListActivity


Android ListActivity Tutorial and Examples.

A ListActivity is an activity that displays a list of items by binding to a data source such as an array or Cursor. ListActivity also exposes to us event handlers when the user selects an item.

This is a class that derives from the Activity class. ListActivity is meant to be used when you plan to use a ListView. In fact it does host a ListView object that can be bound to different data sources, typically either an array or a Cursor holding query results.

ListActivity API Definition

ListActivity, as we've said derives from the Activity class.

public class ListActivity extends Activity 

Here's it's inheritance hierarchy:

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity
                   ↳    android.app.ListActivity

List Activity Subclasses

Here are the classes that derive from ListActivity:

No. Class Description
1. LauncherActivity A class that Displays a list of all activities which can be performed for a given intent. Launches when clicked.
2. PreferenceActivity The base class for an activity to show a hierarchy of preferences to the user.

Screen Layout

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code)

Optionally, your custom view can contain another view object of any type to display when the list view is empty. This "empty list" notifier must have an id "android:id/empty". Note that when an empty view is present, the list view will be hidden when there is no data to display.

The following code demonstrates an (ugly) custom screen layout. It has a list with a green background, and an alternate red "no data" message.

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:paddingLeft="8dp"
         android:paddingRight="8dp">

     <ListView android:id="@android:id/list"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="#00FF00"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>

     <TextView android:id="@android:id/empty"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="#FF0000"
               android:text="No data"/>
 </LinearLayout>

Top Android ListActivity Examples

In this section we will look at several full ListActivity examples.

1. ListActivity and OnItemClick

In this first example we will look at how to populate a ListActivity with data from a simple array. Then we see how to handle OnItemClick events.

API's we use

Let's start by defining the several APIs we will use in this example.

(a). ListActivity

This class belongs to android.app. It is an activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item.

(b). Bundle

Bundle is a mapping from String values to various Parcelable types.

Read about bundle here.

(c). View

This is a class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling.

Read about views here.

(c). ArrayAdapter

An arrayadapter is a concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView.

Read about ArrayAdapter here.

(d). ListView

A ListView is a view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.

Read about ListView here.

package com.codekul.myandroidlistactivity;

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

public class MyListActivity extends ListActivity {

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

        String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
        setListAdapter(adapter);

    }
    @Override
    protected  void  onListItemClick(ListView l, View v, int position, long id){

        String item = (String) getListAdapter().getItem(position);
        Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();

    }
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.codekul.myandroidlistactivity.MyListActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
No. Location Link
1. GitHub Browse
2. GitHub Original Creator: @1sumit

2. ListActivity and ArrayAdapter Example

Let's populate a ListActivity with CatNames then handle Click events. We don't need a layout for this.

package com.denisimusit.listactivity;

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

public class MainActivity extends ListActivity {

    final String[] catNamesArray = new String[] { "Рыжик", "Барсик", "Мурзик",
            "Мурка", "Васька", "Томасина", "Бобик", "Кристина", "Пушок",
            "Дымка", "Кузя", "Китти", "Барбос", "Масяня", "Симба" };
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, catNamesArray);
        setListAdapter(mAdapter);

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
    }
}
No. Location Link
1. GitHub Download
2. GitHub Browse
2. GitHub Original Creator: @disiol

3. ListActivity with AsyncTask


import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Adapter;
import android.widget.ListView;

import java.util.List;

public final class AppPickerActivity extends ListActivity {

  private AsyncTask<Object,Object,List<AppInfo>> backgroundTask;

  @Override
  protected void onResume() {
    super.onResume();
    backgroundTask = new LoadPackagesAsyncTask(this);
    backgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

  @Override
  protected void onPause() {
    AsyncTask<?,?,?> task = backgroundTask;
    if (task != null) {
      task.cancel(true);
      backgroundTask = null;
    }
    super.onPause();
  }

  @Override
  protected void onListItemClick(ListView l, View view, int position, long id) {
    Adapter adapter = getListAdapter();
    if (position >= 0 && position < adapter.getCount()) {
      String packageName = ((AppInfo) adapter.getItem(position)).getPackageName();
      Intent intent = new Intent();
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
      intent.putExtra("url", "market://details?id=" + packageName);
      setResult(RESULT_OK, intent);
    } else {
      setResult(RESULT_CANCELED);      
    }
    finish();
  }

}

4. ListActivity - Click to Open New Activity

This is a ListActivity example where we look at how to show items in a ListActivity. Then when the user clicks a single item we open a new activity.

package com.example.paulorogerio.friendgreeting;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity {

    String[] names;

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

        names = getResources().getStringArray(R.array.friends);
        setListAdapter(new ArrayAdapter<String>(this, R.layout.friend_item, names));

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent in = new Intent(this, SecondActivity.class);

        in.putExtra("message", getString(R.string.show_greetings)+ " " + names[(int) id] + "!" );

        startActivity(in);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
package com.example.paulorogerio.friendgreeting;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class SecondActivity extends Activity {

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

        Intent in = getIntent();

        TextView txtName = (TextView) findViewById(R.id.txtGreetingName);
        txtName.setText(in.getStringExtra("message"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="54dp" />

</RelativeLayout>
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.paulorogerio.friendgreeting.SecondActivity">

    <TextView android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center_vertical|center_horizontal"
        android:id="@+id/txtGreetingName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="55dp" />

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:text="Friend Name"
    android:gravity="center_vertical|center_horizontal"
    android:textSize="24sp"
    android:padding="20dp">

</TextView>
No. Location Link
1. GitHub Download
2. GitHub Browse
2. GitHub Original Creator: @paulonova

5. ListActivity - Populate From XML stored in Assets

In this example we will look at how to use XmlPullParser to parse XML document stored in the Assets directory of our application. We will then show the parsed xml results which will comprise images and text in our ListActivity.

We will be loading from our XML document title, link and images into our ListView. We will open our XML from the assets folder into an InputStream. Then we will have a ParseXML() method which will parse our XML using the XmlPullParser.

ImagesAdapter class will adapt the images and text from the XML into the a custom ListView. It will use the ArrayAdapter as the base adapter class.

This ParseXML is the main activity.

package com.example.parsexml;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;

public class ParseXML extends Activity {
    InputStream xmlStream;
    ArrayList<ItemData> list;
    XMLHandler handler;
    ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse_xml);
        try {
            xmlStream = this.getAssets().open("ItemXML.xml");
            ParseXML();
            list = handler.getItemList();
            LoadImagesFromUrl();
            ImageAdapter adapter = new ImageAdapter(ParseXML.this, R.layout.imagelist, list);
            listView = (ListView) findViewById(R.id.imageList);
            listView.setAdapter(adapter);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_parse_xml, menu);
        return true;
    }

    public void ParseXML(){

        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader reader = sp.getXMLReader();
            handler = new XMLHandler();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(xmlStream));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void LoadImagesFromUrl(){
        for (int i=0; i<list.size();i++){
            LoadChart loader = new LoadChart(ParseXML.this, list.get(i).link);
            loader.execute();
            list.get(i).bitmap = loader.getBitmap();
        }
    }
}

This is the model class and represents a single XML element that will comprise our ListView item. We will have title, link as well as bitmap.

package com.example.parsexml;

import android.graphics.Bitmap;

public class ItemData {
    String title;
    String link;
    Bitmap bitmap;
    public Bitmap getBitmap() {
        return bitmap;
    }
    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getLink() {
        return link;
    }
    public void setLink(String link) {
        this.link = link;
    }

}

This is the custom adapter class, deriving from the ArrayAdapter. It uses the ViewHolder pattern to hold the views to be recycled. That ViewHolder is just a simple class to hold TextView and ImageView widgets for recycling, instead of them being inflated everytime the getView() method is called.

package com.example.parsexml;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ImageAdapter extends ArrayAdapter{
    ViewHolder holder;
    Context ctx;
    List<ItemData> list;
    LoadChart loader;
    public ImageAdapter(Context context, int textViewResourceId,
            List<ItemData> objects) {
        super(context, textViewResourceId, objects);
        ctx = context;
        list = objects;

        // TODO Auto-generated constructor stub
    }
    private class ViewHolder{
        TextView titleView;
        ImageView img;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.imagelist, null);
            holder = new ViewHolder();
            holder.img = (ImageView) convertView.findViewById(R.id.linkimage);
            holder.titleView = (TextView) convertView.findViewById(R.id.title);

            convertView.setTag(holder);

        }
        else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.titleView.setText(list.get(position).title);
        loader = new LoadChart(ctx, holder.img, list.get(position).link);
        loader.execute();

        return convertView;

    }

}

This class will derive from the org.xml.sax.helpers.DefaultHandler class. DefaultHandler is the Default base class for SAX2 event handlers. In this class we override several methods like the startElement(), endElement() and characters().

package com.example.parsexml; 

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLHandler extends DefaultHandler{
    private ArrayList<ItemData> itemList = new ArrayList<ItemData>();
    String value = "";
    ItemData item = null;
    Boolean flag = false;

    public ArrayList<ItemData> getItemList() {
        return itemList;
    } 

    public void setItemList(ArrayList<ItemData> itemList) {
        this.itemList = itemList;
    } 

    @Override 
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub 
        if(flag){
            value = new String(ch, start, length);
        } 
    } 

    @Override 
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub 
        flag = false;

        if(localName.equalsIgnoreCase("title")){
            item.setTitle(value);
        } 
        if(localName.equalsIgnoreCase("link")){
            item.setLink(value);
        } 
        if(localName.equalsIgnoreCase("item")){
            itemList.add(item);
        } 

    } 

    @Override 
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub 
        flag = true;
        value = "";
        if(localName.equalsIgnoreCase("item")){
            item = new ItemData();

        } 
    } 

} 

This class will derive from the abstract asynctask class. Thus this allows us load our XML in a separate thread.

package com.example.parsexml;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class LoadChart extends AsyncTask<Void, Void, Bitmap> {
    private ImageView img;
    private Context con;
    static String urlString ;
    Bitmap bitmap= null;

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public LoadChart(Context context, ImageView img1, String url) {
        this.img = img1;
        this.con = context;
        urlString = url;
    }

    public LoadChart(Context context, String url) {
        this.urlString = url;
        this.con = context;
    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
    }

    @Override
    protected Bitmap doInBackground(Void... params) {

        Bitmap bitmap = DownloadImage();

        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        this.bitmap = bitmap;
        //img.setImageBitmap(bitmap);

    }

    private static InputStream OpenHttpConnection(String urlString)
            throws IOException {

        Log.d("palval", "OpenHttpConnection");
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();

            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }

            String res = Integer.toString(response);
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    public static Bitmap DownloadImage() {
        Log.d("palval", "DownloadImage");
        Bitmap bitmap = null;
        InputStream in = null;
        try {

             //in = OpenHttpConnection("https://chart.googleapis.com/chart?chs=440x220&chd=t:60,40&cht=p3&chl=Hello|World");
            in = OpenHttpConnection(urlString);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;
    }

}
No. Location Link
1. GitHub Download
2. GitHub Browse
2. GitHub Original Creator: @bansal2211

Full ListActivity Examples.

Let's look at some examples.

Android ListActivity Images Text

This is an android custom listview tutorial.How to show images and text in a listview.We are using arrayadapter as our adapter of choice.We also see how to handle custom listview itemclicks.

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