Asim
Asim

Reputation: 7114

Custom Class not working properly

This is a very weird problem. I'll just post the code directly:

package com.asim.contactspull;

    public class Contact
    {
    private String name;
    private String number;

    public Contact(String sname, String snumber)
    {
        this.name = sname;
        this.number = snumber;
    }
    }

The above is my custom class. Following is my MainActivity:

package com.asim.contactspull;

public class MainActivity extends Activity
{
    ArrayList<Contact> contactList;
    ListView contacts;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        contactList = new ArrayList<Contact>();

        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
        while (phones.moveToNext())
        {
            Contact c = new Contact(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)), phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
            Log.d("Contact: ", "" + c.toString());
            contactList.add(c);
        }
        phones.close();

        contacts = (ListView) findViewById(R.id.contacts);
        ArrayAdapter<Contact> aa = new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_1, contactList);
        contacts.setAdapter(aa);
    }
}

When I run the above code, I get entries like this in my ListView:

com.asim.contactspull Contact@405206e8

What am I doing wrong?

Upvotes: 0

Views: 79

Answers (2)

Thomas
Thomas

Reputation: 2767

I think that the problem is that your class has 2 attributes, so your adapter is printing both of them (name and phone).

One option could be to have the ArrayAdapter of an array just with the names. Or write a custom adapter. In the other hand, a custom toString on your custom class could also solve the problem.

Upvotes: 1

Tomislav Novoselec
Tomislav Novoselec

Reputation: 4620

you need to override toString() method to get a proper representation of your class.

like this:

public String toString(){
   return this.name;
}

Upvotes: 1

Related Questions