I am using this code to add ArrayList into 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);
I check in debugger mode it successfully adds contact into contactsList, but I use this code to retrieve it:
ArrayList<String> list = contactsList.get(0);
It returns an empty arraylist.
Full code
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;
}
}
contactListhas one element and that one elementlisthas 3 elements.ArrayList<ArrayList<String>> contactsList = new ArrayList<ArrayList<String>>();go forList<List<String>> contactsList = new ArrayList<>();... you dont need to repeat the type information the right hand side; and on the other hand, you dont want to use the specific implementation class name as type on the left hand side.