Unable to get presence of roster by using smack, openfire

Le Hoang Long picture Le Hoang Long · Dec 17, 2009 · Viewed 11.6k times · Source

I am new to smack API. I am trying to develop a chat application where I was trying for setting and getting the presence.

When I change the presence of a user, its working perfectly fine and it is getting reflected in the Openfire Server.

But when I tries to get the Presence of a user, I am always getting the status as 'unavailable' even if his presence in openfire is showing as 'available'.

I am using the following code to set the status.

        Presence presence = new Presence(Presence.Type.available);
        presence.setStatus("Online, Programmatically!");
        presence.setPriority(24);
        presence.setMode(Presence.Mode.available);
        user.getConnection().sendPacket(presence);

I am using the Roster class to get the presence as follows.

Roster roster = avatar.getRoster();
Collection<RosterEntry> entries = roster.getEntries();

for(RosterEntry rosterEntry: entries) {
    String user = rosterEntry.getUser();

    Presence presence = roster.getPresence(user);

    System.out.println("Presence : "+presence);                                     // 1
    System.out.println("Presence type: "+presence.getType());                // 2
    System.out.println("Presence mode: "+presence.getMode());             // 3

}

Line No 1 alwasys gives 'unavailable' while line number 2 and 3 always give null

I am not able to figure out the cause of this problem. Please help me to resolve this issue.

Thanks in advance.

Answer

Andrea Motto picture Andrea Motto · Sep 16, 2012

Using RosterListener is the proper solution to this problem. There is no reason that code should have a Thread.sleep() in order to make it work properly.

Roster roster = con.getRoster();
roster.addRosterListener(new RosterListener() {
    // Ignored events public void entriesAdded(Collection<String> addresses) {}
    public void entriesDeleted(Collection<String> addresses) {}
    public void entriesUpdated(Collection<String> addresses) {}
    public void presenceChanged(Presence presence) {
        System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
    }
});

(source: http://www.igniterealtime.org/builds/smack/docs/latest/documentation/roster.html)