I'm working on an assignment that requires me to display both the name and number in a single row. I tried creating a custom class, Contact, in order to house the string, Name and Number. The code is pasted below:
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//1. The class ContactsContract allows access to various types of data stored in the phone
//Examples: Contacts, Phone settings, Contact groups etc.
//Creates cursor to search contacts
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//Creates array to store string (names from contact)
ArrayAdapter<Contact> list = new ArrayAdapter<Contact>(this,
R.layout.activity_main);
//2. Using the ContactsContract class above, we got a cursor to the data. Now we iterate through it to get all the data
while (cursor.moveToNext()) {
//3. In our example, we get the DISPLAY_NAME but other data elements are also available
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact newContact = new Contact();
newContact.setName(name);
newContact.setNumber(number);
list.add(newContact);
}
setListAdapter(list);
}
}
And this is my contact class:
public class Contact {
private String name;
private String number;
void setName(String Name){
name = Name;
}
void setNumber (String Number){
number = Number;
}
}