I have created the following method, to add a name and number for every contact within the user's phone book:
PlayerDetails contactPlayer = new PlayerDetails();
public PlayerList getContacts(){
ContentResolver cr = calledActivity.getContentResolver();
Cursor contactList = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (contactList.moveToNext()){
contactPlayer.name = contactList.getString(contactList.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactPlayer.number = contactList.getString(contactList.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
playerNameNumber.myPlayers.add(pos,contactPlayer);
//playerNameNumber.add(pos,name + " " + phoneNumber);
pos++;
}
return playerNameNumber;
}
But each position contains the same data. When I debug, I can see that during the while loop that it is going through each contact, at contactPlayer.name and number it has a different contact each time but at the : playerNameNumber.myPlayers.add it will add the data but to each position. So playerNameNumber[0] and playerNameNumber[1] have the same contact information?!
playerNameNumber is an object with the following:
ArrayList<PlayerDetails> myPlayers = new ArrayList<>();
void addPlayer(PlayerDetails player){
myPlayers.add(player);
}
myPlayers:
int id;
String name;
String number;
Is it the while loop that is causing this issue? also, I know I have 'pos' but I am sure I don't need this?
Why is it the 'add' is replacing every item in the arraylist with the same data?