powered by Jive Software

Cannot compare user's presence with a String, even with toString()

Hi,

A few times in my program I need to differentiate between available and unavailable users. I have an array (called rosterarray) containing all the JIDs of buddies and I’m trying to split them in to 3 arrays (online, offline and away).

I am using this code:

void sortRosterList() {

Log.i(“roster”, “Starting to sort roster list…”);

ArrayList online = new ArrayList();

ArrayList away = new ArrayList();

ArrayList offline = new ArrayList();

int size = rosterarray.size();

int count= 0;

while (count < size){

String presence =$roster.getPresence(rosterarray.get(count)).toString();

Log.i(“roster”, roster.getEntry(rosterarray.get(count)).getName() + " is ‘" + presence + "’");

if (presence == “available”) {

$online.add(rosterarray.get(count));

}

else if (presence == “available: away”) {

$away.add(rosterarray.get(count));

}

else if (presence == “unavailable”) {

$offline.add(rosterarray.get(count));

}

count = count + 1;

}

The log file shows all the different presences. And from this and another instance in my code I think that the problem is when comparing presence to a String…it just doesnt want to know!..even when using toString().

Surely using if (presence == “available”) should be fine…it’s just comparing 2 strings however it’s not working! I am new to both Java and Smack so any help would be GREATLY appreciated.

Thanks for any help.

Hi,

comparing the presence via the String representation is generallly a bad idea. The toString() method should only be used to output a representation of an object but not for program logic. To compare the different types and modes of a presence instance you shoud compare with the presences enums. So the code for splitting all presences in the three categories should look something like this:

for (String jid : rosterarray) {
    Presence presence = $roster.getPresence(jid);
    Log.i("roster", $roster.getEntry(jid).getName()
                    + " is '" + presence + "'");
    // if online
    if(presence.getType() == Presence.Type.available) {
        // if available or free for chat
        if(presence.getMode() == Presence.Mode.available || presence.getMode() == Presence.Mode.chat) {
            $online.add(jid);
        } else {
            $away.add(jid); // away
        }
    } else {
        $offline.add(jid);
    }
}

BTW: In Java you normally don’t name variables with a $ sign

Best regards,

Henning

Thank you very much for the help…that worked perfectly!. I also leant a lot more about Java from it so thank you again.

P.s I used to write BASIC programs as a kid, thats where I got the $ from .