Android Activity → Android ListActivity – Camposha

Android Activity

Android Activity

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 
         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.

[ui-tabs position=”center” active=”0″ theme=”default”]

[ui-tab title=”MyListActivity.java”]

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();

    }
}

[/ui-tab]
[ui-tab title=”activity_my_list.xml”]

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    
    
    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>

[/ui-tab]
[ui-tab title=”Download”]

No. Location Link
1. GitHub Browse
2. GitHub Original Creator: @1sumit

[/ui-tab]
[/ui-tabs]

2. ListActivity and ArrayAdapter Example

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

[ui-tabs position=”top-left” active=”0″ theme=”default”]

[ui-tab title=”MainActivity.java”]

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);
    }
}

[/ui-tab]
[ui-tab title=”Download”]

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

[/ui-tab]
[/ui-tabs]

3. ListActivity with AsyncTask

[ui-tabs position=”top-left” active=”0″ theme=”default”]

[ui-tab title=”MainActivity.java”]


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();
  }

}

[/ui-tab]
[/ui-tabs]

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.

[ui-tabs position=”top-left” active=”0″ theme=”badge”]

[ui-tab title=”MainActivity.java”]

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);
    }
}

[/ui-tab]

[ui-tab title=”SecondActivity.java”]

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);
    }
}

[/ui-tab]
[ui-tab title=”activity_main.xml”]

<RelativeLayout 
    
    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>

[/ui-tab]
[ui-tab title=”activity_second.xml”]

<RelativeLayout 
     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>

[/ui-tab]
[ui-tab title=”friend_item.xml”]

<?xml version="1.0" encoding="utf-8"?>
<TextView 
    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>

[/ui-tab]
[ui-tab title=”Download”]

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

[/ui-tab]
[/ui-tabs]

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.

[ui-tabs position=”top-left” active=”0″ theme=”default”]

[ui-tab title=”ParseXML.java”]
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();
        }
    }
}

[/ui-tab]

[ui-tab title=”ItemData.java”]
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;
    }

}

[/ui-tab]
[ui-tab title=”ImageAdapter.java”]
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;

    }

}

[/ui-tab]
[ui-tab title=”XMLHandler.java”]
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();

        } 
    } 

} 

[/ui-tab]
[ui-tab title=”LoadChart.java”]
This class will derive from the abstract asynctask class. Thus this allows us load our XML in a separate thread.

Download

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

 

 

Leave a Reply

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

X