【问题标题】:How can i add object into static array如何将对象添加到静态数组中
【发布时间】:2014-08-11 20:51:13
【问题描述】:

代码思路原来是这样的,我想从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;
    }
}

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

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

    public static List<Person> PEOPLE(ContentResolver cr) {
    
        ArrayList<Person> people = new ArrayList<Person>();
        ...
        while (cursor.moveToNext()) {
           ...
           people.add(new Person(...);
        }     
    
        return people;
    }
    

    要遍历列表,可以使用 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);
        ...
    

    【讨论】:

    • 你的意思是什么? for 循环?
    • 应该通过解析器“for (int i = 0; i
    • 是的,它是一种方法。在这种情况下,忘记for (int i = 0 循环。它会每次都调用该方法,而您不希望这样。
    • @matiash 你太棒了! ,现在测试所以循环应该像这样运行? "for (Person person : People.PEOPLE(cr))"
    • @HanyAlsamman 迭代时(使用for(item : collection))你没有索引,但你有项目。如果您需要索引,我已经发布了另一个示例。
    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    相关资源
    最近更新 更多