DommyCastles
DommyCastles

Reputation: 425

Android adding to an arraylist

I have a chat program that displays I list of online users. The message back from the server is "RESP_USERLIST,,, etc. Except I am having problems adding these usernames to my list.

Here is my current code:

List <String> responseList = Arrays.asList(OnlineUsersPost.split(","));
    if (responseList.contains("RESP_USERLIST")){
        _onlineUsers = responseList.get(1);

        System.out.println("Online users: " + _onlineUsers);

And where I initialise it:

private String _onlineUsers;

It seems it is only taking the first user and adding it to the list, I want to add them all to an arraylist.

EDIT: I have now tried it this way, with little difference:

List <String> responseList = Arrays.asList(OnlineUsersPost.split(","));
    if (responseList.contains("RESP_USERLIST")){
        for (int i = 0; i < responseList.size(); i++) {
            _onlineUsers.add(responseList.get(i));
            System.out.println("Online users: " + _onlineUsers);
        }

And where I initialise it:

private List<String> _onlineUsers;

Upvotes: 0

Views: 462

Answers (1)

jeet
jeet

Reputation: 29199

I think You should initialize your arraylist first, initialization statement you are showing is only declaration, so initialize it as:

private List<String> _onlineUsers= new ArrayList<Sting>();

and change your loop to following:

ist <String> responseList = Arrays.asList(OnlineUsersPost.split(","));
    if (responseList.contains("RESP_USERLIST")){
        for (int i = 1; i < responseList.size(); i++) {
            _onlineUsers.add(responseList.get(i));
            System.out.println("Online users: " + _onlineUsers);
        }

Upvotes: 1

Related Questions