如何将对象添加到静态数组中

时间:2014-06-21 04:50:57

标签: android android-arrayadapter android-contacts android-cursor

代码的想法最初是这样的,我想添加来自android联系人的人

public final class People{
        public static Person[] PEOPLE = {
        new Person(1, R.drawable.person1, "Betty Boo", "is having her hair cut at 6pm"),
        new Person(1, R.drawable.person2, "Lisa James", "is going to Avicii live ft.. event"),
        };
}

活动

    ViewGroup people = (ViewGroup) findViewById(R.id.people);
    for(int i = 0; i < People.PEOPLE.length; i++){
            people.addView(People.inflatePersonView(this, people, People.PEOPLE[i]));
    }

我想将这些项目放入查询数组中,我的尝试如下

public final class People{


    public static Person[] PEOPLE(ContentResolver cr) {

        Person[] PEOPLE = {};

        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "starred=?",
                        new String[] {"1"}, null);

        int i=0;
        int contactID;
        String contactName;
        while (cursor.moveToNext()) {

            contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));

            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            PEOPLE[i] = new Person(contactID, R.drawable.person1, contactName, contactName);

            i++;
        }
        cursor.close();

        return PEOPLE;
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

数组不是最合适的数据结构,因为它无法调整大小以添加新元素(嗯,它可以,但实际上你需要创建一个新数组并复制内容 - 绝对不是适合逐个添加物品。)

我建议改为使用List<Person>(使用ArrayListLinkedList作为实际类)。或多或少是这样的:

public static List<Person> PEOPLE(ContentResolver cr) {

    ArrayList<Person> people = new ArrayList<Person>();
    ...
    while (cursor.moveToNext()) {
       ...
       people.add(new Person(...);
    }     

    return people;
}

要迭代List,可以使用for循环:

for (Person person : People.PEOPLE(cr)) {
    ... person

或者,如果您愿意,还可以使用更传统的

List<Person> people = People.PEOPLE(cr);
for (int i = 0; i < people.size(); i++) {
    Person person = people.get(i);
    ...