gpt4 book ai didi

java - 在ArrayList中添加ArrayList并检索它

转载 作者:行者123 更新时间:2023-12-01 17:58:31 25 4
gpt4 key购买 nike

我正在使用此代码将 ArrayList 添加到 ArrayList>

ArrayList<String> contact = new ArrayList<String>();
ArrayList<ArrayList<String>> contactsList = new ArrayList<ArrayList<String>>();
contact.add("name1");
contact.add("name2");
contact.add("name3");
contactsList.add(contact);

我在调试器模式下检查它成功将联系人添加到 contactsList 中,但我使用此代码来检索它:

ArrayList<String> list = contactsList.get(0);

它返回一个空数组列表。

完整代码

public class ContactsFragment extends Fragment {

ArrayList<ArrayList<String>> contactsList = new ArrayList<ArrayList<String>>();
ArrayList<String> contactList = new ArrayList<String>();

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

ContentResolver resolver = getActivity().getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactList.add(name);
Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(phoneNumber);
}

contactsList.add(contactList);
contactList.clear();


}

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

String data = "";

for (int i = 0; i < contactsList.size(); i++) {
ArrayList list = new ArrayList();
list.add(contactsList.get(i));
for (int q = 0; q < list.size(); q++) {
data = data + list.get(q) + "\n";
}
data = data + "\n\n";
}

builder.setMessage(data);
builder.create();
builder.show();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);

return rootView;
}

}

最佳答案

您的变量只是一个拼写错误。您将联系人数据添加到 contactsList 上,然后移交 contactList 中的索引元素“0”(不带 s)。

编辑:如果您想使用联系人列表,您可能应该创建一个自己的类 Contact ,您可以在其中构建单独的对象。列表中的列表逻辑和约定可能非常困惑并且容易出错。

Contact c1 = new Contact("Name1");
Contact c2 = new Contact("Name2");
Contact c3 = new Contact("Name3");

ArrayList<Contact> contactList = new ArrayList<Contact>();
contactList.add(c1);
contactList.add(c2);
contactList.add(c3);

for (int i = 0; i < contactList.size(); i++) {
System.out.println(contactList.get(i).name1);
// your code...
}

关于java - 在ArrayList中添加ArrayList并检索它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42764538/

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