gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:50:11 25 4
gpt4 key购买 nike

代码思路本来是这样的,我想添加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"),
};
}

在 Activity 中

    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;
}
}

谢谢!

最佳答案

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

我建议使用 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;
}

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

关于android - 如何将对象添加到静态数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24338405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com