How to use ArrayAdapter


ArrayList<MyClass> myList = new ArrayList<MyClass>();

ListView listView = (ListView) findViewById(;

ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this, R.layout.row,
    to, myList.);

Class: MyClass

class MyClass {
    public String reason;
    public long long_val;

I have created row.xml in layouts, but don't know how to show both reason and long_val in the ListView using ArrayAdapter.

3/23/2013 5:25:13 PM

Accepted Answer

Implement custom adapter for your class:

public class MyClassAdapter extends ArrayAdapter<MyClass> {

    private static class ViewHolder {
        private TextView itemView;

    public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
        super(context, textViewResourceId, items);

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(this.getContext())
            .inflate(R.layout.listview_association, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.itemView = (TextView) convertView.findViewById(;

        } else {
            viewHolder = (ViewHolder) convertView.getTag();

        MyClass item = getItem(position);
        if (item!= null) {
            // My layout has only one TextView
                // do whatever you want with your string and long
            viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));

        return convertView;

For those not very familiar with the Android framework, this is explained in better detail here:

10/20/2016 2:31:06 AM

You could just add a toString() method to MyClass, per

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

class MyClass {

 public String toString() {
  return "Hello, world.";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow