views:

562

answers:

2

ArrayList myList = new ArrayList();

ListView listView = (ListView) findViewById(R.id.list);

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

Class: MyClass

class MyClass {
 public String reason;
 public long long_val;
}

I want to show this in listView. I have created row.xml in layouts, but don't know how to show both String and long.converted into toString() in the ListView using ArrayAdapter.

Please Help me.

+1  A: 

Hi,

Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.

Klarth
+5  A: 

Implement custom adapter for your class:

public class MyClassAdapter extends ArrayAdapter<MyClass> {

    private ArrayList<MyClass> items;
    private Context context;

    public MessageAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
        super(context, textViewResourceId, items);
        this.context = context;
        this.items = items;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.item, null);
        }

        MyClass item = items.get(position);
        if (item!= null) {
            // My layout has only one TextView
            TextView itemView = (TextView) view.findViewById(R.id.ItemView);
            if (itemView != null) {
                // do whatever you want with your string and long
                itemView.setText(String.format("%s %d", item.reason, item.long_val));
            }
         }

        return view;
    }
}
Nikola Smiljanić
BUt MyClass item = item.get(position); through error, that method get(int) is not in Class MyClass.
Sumit M Asok
Sorry, MyClass item = items.get(position) solves the error, mismatches variables by me.
Sumit M Asok