powered by Jive Software

The custom extension data missing on receiving end

Hi
I’m using smack version 4.1.4.
When I’m sending custom extension using addExtension() method to send an image name like this
<imagename xmlns='ns:beep'>97_96b784cfe3e4b2c880e531b96ec53689.jpg</imagename>

But on the receiving end of the Listener I’m only receiving like this
<imagename xmlns='ns:beep'></imagename>

Please help me to solve this issue. I’m currently working on a live project, that needs to be updated soon.

Can you give some more information, like implementation details about your ExtensionElement and ElementProvider?

My Extension Element class be like this

public class ImgMessageModel implements ExtensionElement {

    String Element = "imagename";
    String ImageName;
    String nameattr = "imgname";
    String NameSpace = "ns:beep";

    @Override
    public String getElementName() {
        return Element;
    }

    @Override
    public CharSequence toXML() {
        XmlStringBuilder xml = new XmlStringBuilder(this);
        /*xml.append(">");
        xml.append(getImageName());
        xml.closeElement(getElementName());*/

        /*xml.attribute(nameattr, getImageName());
        xml.closeEmptyElement();*/

        String str = String.format("<imagename xmlns='ns:beep'>%s</imagename>", ImageName);
        return str;

        //return xml;
    }
}

And i’m sending a message packet like this…
<message xml:lang='en' from='21-21021_1510812658271@platesapp.m.in-app.io/Android' to='13-92919_1515397784307@platesapp.m.in-app.io/Android' type='chat' id='fXy38-231'><archived by='21-21021_1510812658271@platesapp.m.in-app.io' id='1564579408285525' xmlns='urn:xmpp:mam:tmp'/><stanza-id by='21-21021_1510812658271@platesapp.m.in-app.io' id='1564579408285525' xmlns='urn:xmpp:sid:0'/><imagename xmlns='ns:beep'>97_96b784cfe3e4b2c880e531b96ec53689.jpg</imagename><body>Sent you a image.</body><thread>e6cf1e8e-5bd1-447e-b6c2-d6c5ac049af3</thread></message>

But on the receiving end i’m receiving like this

<message to='21-21021_1510812658271@platesapp.m.in-app.io/Android' from='13-92919_1515397784307@platesapp.m.in-app.io/Android' id='fXy38-231' xml:lang='en' type='chat'><body>Sent you a image.</body><thread>e6cf1e8e-5bd1-447e-b6c2-d6c5ac049af3</thread><archived xmlns='urn:xmpp:mam:tmp'></archived><stanza-id xmlns='urn:xmpp:sid:0'></stanza-id><imagename xmlns='ns:beep'></imagename><customize xmlns='p1:push:customize'></customize></message>

And i’m adding the extension element to the message like this

ImgMessageModel imgelement = new ImgMessageModel();
imgelement.setImageName(ImgName);
message.addExtension(imgelement);

To be clear, the receiving end is a Smack based client as well?
If that is the case, please share your Provider class as well :slight_smile:

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.platesapp.Config;
import com.platesapp.DB.dbhandler;
import com.platesapp.Main_Activity;
import com.platesapp.datamodels.Chat_Model;
import com.platesapp.datamodels.ImgMessageModel;
import com.platesapp.datamodels.MessageModel;
import com.platesapp.datamodels.RegIQModel;
import com.platesapp.datamodels.jabber_frnds_model;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.filter.StanzaTypeFilter;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.roster.RosterListener;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.delay.packet.DelayInformation;
import org.jivesoftware.smackx.iqregister.AccountManager;
import org.jivesoftware.smackx.ping.PingFailedListener;
import org.jivesoftware.smackx.ping.PingManager;
import org.jivesoftware.smackx.vcardtemp.VCardManager;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

/**
 * Created by Ankit on 10/3/2015.
 */
public class MyXMPP_Test {

    /*private static final String DOMAIN = "localhost";
    private static final String HOST = "platesapp.net";*/
    private static final String DOMAIN = Config.jid_host;
    private static final String HOST = Config.jid_host;
    private static final int PORT = 5222;
    private String userName = "";
    private String passWord = "";
    AbstractXMPPConnection connection;
    ChatManager chatmanager;
    Chat newChat;
    XMPPConnectionListener connectionListener = new XMPPConnectionListener();
    private boolean connected;
    private boolean isToasted;
    private boolean chat_created;
    private boolean loggedin;
    private ChatMessageListener messageListener;
    Context mApplicationContext;

    public MyXMPP_Test(Context context) {
        mApplicationContext = context;
    }


    //Initialize
    public void init(String userId, String pwd) {
        Log.i("XMPP", "Initializing!");
        this.userName = userId;
        this.passWord = pwd;
        XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
        //if (userName != null && passWord != null)
        if (!userName.equals("") && !passWord.equals(""))
            configBuilder.setUsernameAndPassword(userName, passWord);
        configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        configBuilder.setResource("Android");
        configBuilder.setServiceName(DOMAIN);
        configBuilder.setHost(HOST);
        configBuilder.setPort(PORT);
        configBuilder.setDebuggerEnabled(true);
        connection = new XMPPTCPConnection(configBuilder.build());
        connection.addConnectionListener(connectionListener);

    }

    public boolean isConnectedXMPP() {
        return connection.isConnected();
    }

    public void sendRegStanza(String RegID) {
        RegIQModel data = new RegIQModel(RegID);
        Log.d("Reg_INFO", data.toString());
        try {
            connection.sendStanza(data);
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
    }

    public boolean login(String name, String passWord) {
        try {
            connection.login(name, passWord);
            return true;
        } catch (XMPPException e) {
            e.printStackTrace();
            return false;
        } catch (SmackException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void sendBlankPacket() {

    }

    public boolean create_Account(String name, String Password) {
        boolean created;
        AccountManager manager = AccountManager.getInstance(connection);
        try {
            manager.sensitiveOperationOverInsecureConnection(true);
            manager.createAccount(name, Password);
            created = true;
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
            created = false;
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
            created = false;
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            created = false;
        }
        try {
            connection.login(name, Password);
        } catch (XMPPException e) {
            e.printStackTrace();
        } catch (SmackException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return created;
    }
    

    // Disconnect Function
    public void disconnectConnection() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                connection.disconnect();
            }
        }).start();
    }

    public void connectConnection() {
        AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(Void... arg0) {

                // Create a connection
                try {
                    connection.connect();
                    //login();
                    connected = true;
                    Roster roster = Roster.getInstanceFor(connection);
                    roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
                    roster.addRosterListener(new RosterListener() {
                        @Override
                        public void entriesAdded(Collection<String> addresses) {
                            Log.d("ROSTER_ADDED", addresses.toString());
                        }

                        @Override
                        public void entriesUpdated(Collection<String> addresses) {
                            Log.d("ROSTER_UPDATED", addresses.toString());
                        }

                        @Override
                        public void entriesDeleted(Collection<String> addresses) {
                            Log.d("ROSTER_DELETED", addresses.toString());
                        }

                        @Override
                        public void presenceChanged(Presence presence) {
                            //Update VCard inside if
                            Log.d("ROSTER_CHANGED", presence.toString());
                            if (presence.hasExtension("x", "vcard-temp:x:update")) {
                                if (presence.getType() == Presence.Type.available) {
                                    dbhandler dbhandler = new dbhandler(Main_Activity.activity);
                                    dbhandler.updateVcard(presence.getFrom().split("/")[0]);
                                }
                            }
                        }
                    });
                    connection.addSyncStanzaListener(new StanzaListener() {
                        @Override
                        public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
                            Log.d("saraPacket", packet.toString());
                            Presence presence = (Presence) packet;
                            final RosterEntry newEntry = getRoster().getEntry(presence.getFrom());
                            if (presence.getType() == Presence.Type.subscribe) {
                                Presence subscribed = new Presence(Presence.Type.subscribed);
                                subscribed.setTo(presence.getFrom());
                                Presence subscribe = new Presence(Presence.Type.subscribe);
                                subscribe.setTo(presence.getFrom());
                                if (newEntry == null) {
                                    connection.sendStanza(subscribe);
                                    connection.sendStanza(subscribed);
                                } else {
                                    connection.sendStanza(subscribed);
                                }
                                VCardManager cardManager = VCardManager.getInstanceFor(connection);
                                VCard vCard = null;
                                try {
                                    vCard = cardManager.loadVCard(presence.getFrom());
                                } catch (SmackException.NoResponseException e) {
                                    e.printStackTrace();
                                } catch (XMPPException.XMPPErrorException e) {
                                    e.printStackTrace();
                                }
                                if (vCard != null) {
                                    dbhandler dbhandler = new dbhandler(mApplicationContext);
                                    //vCard.get
                                    Log.e("VCard_Suffix", vCard.getSuffix());
                                    jabber_frnds_model data = new jabber_frnds_model(presence.getFrom(), vCard.getEmailHome(), vCard.getNickName(), vCard.getAvatarHash(), "0", vCard.getOrganization(), vCard.getOrganizationUnit(), vCard.getAvatar());
                                    dbhandler.addJabberUser(data);
                                    dbhandler.close();
                                    Log.d("vcardsara", vCard.toString());
                                }
                            }
                        }
                    }, StanzaTypeFilter.PRESENCE);
                    
                    messageListener = new ChatMessageListener() {
                        @Override
                        public void processMessage(Chat chat, Message message) {

                            //Log.d("SaraMsg:", "From:" + message.getFrom() + " Type:" + message.getType() + " Body:" + message.getBody());
                            SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
                            Date delaydate = getDelay(message);
                            Date date = new Date();
                            if (delaydate != null) {
                                date = delaydate;
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                date = new Date();

                            }
                            Intent intent = new Intent(ConnectXmpp.NEW_MESSAGE);
                            intent.setPackage(mApplicationContext.getPackageName());
                            intent.putExtra(ConnectXmpp.BUNDLE_FROM_JID, message.getFrom());
                            intent.putExtra(ConnectXmpp.BUNDLE_MESSAGE_BODY, message.getBody());
                            Log.d("NEW_MSG", "MSG BROADCASTED " + message.getBody());
                            if (message.getType() == Message.Type.chat) {
                                Collection<ExtensionElement> extensions = message.getExtensions();
                                mApplicationContext.sendBroadcast(intent);
                                dbhandler dbhandler = new dbhandler(mApplicationContext);
                                String msgxml = message.toString();
                                if (msgxml.contains("imagename")) {
                                    String[] imgname = msgxml.substring(msgxml.indexOf("<imagename") + 1, msgxml.indexOf("</imagename>")).split(">");
                                    String imgnamefull = imgname[imgname.length - 1];
                                    Chat_Model data = new Chat_Model(message.getFrom().split("/")[0], message.getTo(), message.getBody(), imgnamefull, Chat_Model.messagegtype.IMAGE, Chat_Model.transaction_type.INCOMING, date);
                                    data.setJid(message.getFrom().split("/")[0]);
                                    dbhandler.addMessage(data);
                                    dbhandler.addmsgcount(message.getFrom().split("/")[0]);
                                } else {
                                    Chat_Model data = new Chat_Model(message.getFrom().split("/")[0], message.getTo(), message.getBody(), Chat_Model.messagegtype.TEXT, Chat_Model.transaction_type.INCOMING, date);
                                    data.setJid(message.getFrom().split("/")[0]);
                                    dbhandler.addMessage(data);
                                    dbhandler.addmsgcount(message.getFrom().split("/")[0]);
                                }
                                dbhandler.close();
                            }
                        }
                    };
                    ChatManager.getInstanceFor(connection).addChatListener(new ChatManagerListener() {
                        @Override
                        public void chatCreated(Chat chat, boolean createdLocally) {
                            chat.addMessageListener(messageListener);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SmackException e) {
                    e.printStackTrace();

                } catch (XMPPException e) {
                    e.printStackTrace();
                }

                return null;
            }
        };
        connectionThread.execute();
    }

    public Date getDelay(Stanza packet) {
        DelayInformation delay = packet.getExtension("delay", "urn:xmpp:delay");
        // If there was no delay based on XEP-0203, then try XEP-0091 for
        // backward compatibility
        if (delay == null) {
            delay = packet.getExtension("x",
                    "jabber:x:delay");
        }
        if (delay == null)
            return null;
        else
            return delay.getStamp();
    }

    public Roster getRoster() {
        Roster roster = Roster.getInstanceFor(connection);
        if (!roster.isLoaded())
            try {
                roster.reloadAndWait();
            } catch (SmackException.NotLoggedInException e) {
                e.printStackTrace();
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        return roster;
    }
    
    public void sendMsg(String jid, String Name, String msg) {
        if (connection.isConnected() == true) {
            // Assume we've created an XMPPConnection name "connection"._
            chatmanager = ChatManager.getInstanceFor(connection);
            newChat = chatmanager.createChat(jid);
            try {
                Message message = new Message();
                message.setBody(msg);
                MessageModel element = new MessageModel();
                element.setNameValue(Name);
                message.addExtension(element);
                Log.e("Message_Packet", message.toXML().toString());
                newChat.sendMessage(message);
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendImage(String jid, String Name, String ImgName) {
        if (connection.isConnected() == true) {
            // Assume we've created an XMPPConnection name "connection"._
            chatmanager = ChatManager.getInstanceFor(connection);
            newChat = chatmanager.createChat(jid);
            try {
                Message message = new Message();
                message.setBody("Sent you a image.");
                //message.addBody("en", ImgName);
                MessageModel element = new MessageModel();
                element.setNameValue(Name);
                //message.addExtension(element);
                ImgMessageModel imgelement = new ImgMessageModel();
                imgelement.setImageName(ImgName);
                message.addExtension(imgelement);
                Collection<ExtensionElement> collection = new ArrayList<>();
                /*chatImageModel chatimgelement = new chatImageModel();
                chatimgelement.setNameValue(ImgName);*/
                collection.add(element);
                collection.add(imgelement);
                message.addExtensions(collection);
                Log.e("Message_Packet", message.toXML().toString());
                newChat.sendMessage(message);
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            }
        }
    }

    public void login() {

        try {
            connection.login(userName, passWord);
            //Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");

        } catch (XMPPException | SmackException | IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //Connection Listener to check connection state
    public class XMPPConnectionListener implements ConnectionListener {
        @Override
        public void connected(final XMPPConnection connection) {

            Log.d("xmpp", "Connected!");
            connected = true;
            if (!connection.isAuthenticated()) {
                login();
            }
        }

        @Override
        public void connectionClosed() {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub


                    }
                });
            Log.d("xmpp", "ConnectionCLosed!");
            connected = false;
            chat_created = false;
            loggedin = false;
        }

        @Override
        public void connectionClosedOnError(Exception arg0) {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {

                    }
                });
            PingManager manager = PingManager.getInstanceFor(connection);
            try {
                manager.pingMyServer(false);
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            }
            Log.d("xmpp", "ConnectionClosedOn Error!");
            connected = false;

            chat_created = false;
            loggedin = false;
        }

        @Override
        public void reconnectingIn(int arg0) {

            Log.d("xmpp", "Reconnectingin " + arg0);

            loggedin = false;
        }

        @Override
        public void reconnectionFailed(Exception arg0) {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {


                    }
                });
            Log.d("xmpp", "ReconnectionFailed!");
            connected = false;

            chat_created = false;
            loggedin = false;
        }

        @Override
        public void reconnectionSuccessful() {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub


                    }
                });
            Log.d("xmpp", "ReconnectionSuccessful");
            connected = true;

            chat_created = false;
            loggedin = false;
        }

        @Override
        public void authenticated(XMPPConnection arg0, boolean arg1) {
            Log.d("xmpp", "Authenticated!");
            loggedin = true;

            chat_created = false;
            PingManager pingManager = PingManager.getInstanceFor(connection);
            pingManager.setPingInterval(10);

            try {
                pingManager.pingMyServer();
                pingManager.pingMyServer(true, 60);
                pingManager.pingServerIfNecessary();
                pingManager.registerPingFailedListener(new PingFailedListener() {
                    @Override
                    public void pingFailed() {
                        Log.d("Ping", "pingFailed");
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }).start();
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub


                    }
                });
        }
    }


}

Have a look at the code

It appears that you did not create and registered a class that implements the
ExtensionElementProvider<ImgMessageModel>.

Your ImgMessageModel class is only responsible for serialization (toXML), but the receiver does not know how to deserialize the XML back into a java object.

Take a look at Smacks provider documentation for more information.

public class ImgMessageModel implements ExtensionElement {

    String Element = "imagename";
    String ImageName;
    String nameattr = "imgname";
    String NameSpace = "ns:beep";

    public String getElement() {
        return Element;
    }

    public void setElement(String element) {
        Element = element;
    }

    public String getImageName() {
        return ImageName;
    }

    public void setImageName(String imageName) {
        ImageName = imageName;
    }

    @Override
    public String getElementName() {
        return Element;
    }

    @Override
    public CharSequence toXML() {
        XmlStringBuilder xml = new XmlStringBuilder(this);
        /*xml.append(">");
        xml.append(getImageName());
        xml.closeElement(getElementName());*/

        /*xml.attribute(nameattr, getImageName());
        xml.closeEmptyElement();*/

        String str = String.format("<imagename xmlns='ns:beep'>%s</imagename>", ImageName);
        return str;

        //return xml;
    }

    @Override
    public String getNamespace() {
        return NameSpace;
    }
}

This is my ImgMessageModel class

Did you even take a look at the link I posted? :smiley:
Your ImgMessageModel class appears to be working correctly. What you are missing is a dedicated ExtensionElementProvider implementation which is responsible for parsing the incoming XML back into the ExtensionElement class (ImgMessageModel in your case) on the receiving side.

Edit: There are plenty of examples within the Smack source code itself for reference. ExtensionElements usually go to a element subpackage, while providers reside in a provider package.

1 Like

I did see the link you’ve posted. I think i still haven;t properly implemented the receiving end. Can I know where to add ProviderManager. In-depth tutorial would be helpful.

  1. Implement your provider (take a look at this one for reference).
  2. On runtime, add the provider to Smacks list of knows ExtensionElementProviders by calling
ProviderManager.addExtensionProvider(ImgMessageModel.Element, ImgMessageModel.NameSpace,
            new ImgMessageProvider());

Hi I have added Extension provider after i connect the connection is MyXMPP_Test class. But i’m still not able to receive the custom extension. What am i still missing?
this is how the function looks after implementing custom extension

public void connectConnection() {
        AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(Void... arg0) {

                // Create a connection
                try {
                    connection.connect();
                    //login();
                    connected = true;

                    ProviderManager.addExtensionProvider(ImgMessageModel.Element, ImgMessageModel.NameSpace, new imageMessageProvider());

                    Roster roster = Roster.getInstanceFor(connection);
                    roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
                    roster.addRosterListener(new RosterListener() {
                        @Override
                        public void entriesAdded(Collection<String> addresses) {
                            Log.d("ROSTER_ADDED", addresses.toString());
                        }

                        @Override
                        public void entriesUpdated(Collection<String> addresses) {
                            Log.d("ROSTER_UPDATED", addresses.toString());
                        }

                        @Override
                        public void entriesDeleted(Collection<String> addresses) {
                            Log.d("ROSTER_DELETED", addresses.toString());
                        }

                        @Override
                        public void presenceChanged(Presence presence) {
                            //Update VCard inside if
                            Log.d("ROSTER_CHANGED", presence.toString());
                            if (presence.hasExtension("x", "vcard-temp:x:update")) {
                                if (presence.getType() == Presence.Type.available) {
                                    dbhandler dbhandler = new dbhandler(Main_Activity.activity);
                                    dbhandler.updateVcard(presence.getFrom().split("/")[0]);
                                }
                            }
                        }
                    });
                    connection.addSyncStanzaListener(new StanzaListener() {
                        @Override
                        public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
                            Log.d("saraPacket", packet.toString());
                            Presence presence = (Presence) packet;
                            final RosterEntry newEntry = getRoster().getEntry(presence.getFrom());
                            if (presence.getType() == Presence.Type.subscribe) {
                                Presence subscribed = new Presence(Presence.Type.subscribed);
                                subscribed.setTo(presence.getFrom());
                                Presence subscribe = new Presence(Presence.Type.subscribe);
                                subscribe.setTo(presence.getFrom());
                                if (newEntry == null) {
                                    connection.sendStanza(subscribe);
                                    connection.sendStanza(subscribed);
                                } else {
                                    connection.sendStanza(subscribed);
                                }
                                VCardManager cardManager = VCardManager.getInstanceFor(connection);
                                VCard vCard = null;
                                try {
                                    vCard = cardManager.loadVCard(presence.getFrom());
                                } catch (SmackException.NoResponseException e) {
                                    e.printStackTrace();
                                } catch (XMPPException.XMPPErrorException e) {
                                    e.printStackTrace();
                                }
                                if (vCard != null) {
                                    dbhandler dbhandler = new dbhandler(mApplicationContext);
                                    //vCard.get
                                    Log.e("VCard_Suffix", vCard.getSuffix());
                                    jabber_frnds_model data = new jabber_frnds_model(presence.getFrom(), vCard.getEmailHome(), vCard.getNickName(), vCard.getAvatarHash(), "0", vCard.getOrganization(), vCard.getOrganizationUnit(), vCard.getAvatar());
                                    dbhandler.addJabberUser(data);
                                    dbhandler.close();
                                    Log.d("vcardsara", vCard.toString());
                                }
                            }
                        }
                    }, StanzaTypeFilter.PRESENCE);
                    
                    messageListener = new ChatMessageListener() {
                        @Override
                        public void processMessage(Chat chat, Message message) {

                            //Log.d("SaraMsg:", "From:" + message.getFrom() + " Type:" + message.getType() + " Body:" + message.getBody());
                            SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
                            Date delaydate = getDelay(message);
                            Date date = new Date();
                            if (delaydate != null) {
                                date = delaydate;
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                date = new Date();

                            }
                            Intent intent = new Intent(ConnectXmpp.NEW_MESSAGE);
                            intent.setPackage(mApplicationContext.getPackageName());
                            intent.putExtra(ConnectXmpp.BUNDLE_FROM_JID, message.getFrom());
                            intent.putExtra(ConnectXmpp.BUNDLE_MESSAGE_BODY, message.getBody());
                            Log.d("NEW_MSG", "MSG BROADCASTED " + message.getBody());
                            if (message.getType() == Message.Type.chat) {
                                Collection<ExtensionElement> extensions = message.getExtensions();
                                mApplicationContext.sendBroadcast(intent);
                                dbhandler dbhandler = new dbhandler(mApplicationContext);
                                String msgxml = message.toString();
                                if (msgxml.contains("imagename")) {
                                    String[] imgname = msgxml.substring(msgxml.indexOf("<imagename") + 1, msgxml.indexOf("</imagename>")).split(">");
                                    String imgnamefull = imgname[imgname.length - 1];
                                    Chat_Model data = new Chat_Model(message.getFrom().split("/")[0], message.getTo(), message.getBody(), imgnamefull, Chat_Model.messagegtype.IMAGE, Chat_Model.transaction_type.INCOMING, date);
                                    data.setJid(message.getFrom().split("/")[0]);
                                    dbhandler.addMessage(data);
                                    dbhandler.addmsgcount(message.getFrom().split("/")[0]);
                                } else {
                                    Chat_Model data = new Chat_Model(message.getFrom().split("/")[0], message.getTo(), message.getBody(), Chat_Model.messagegtype.TEXT, Chat_Model.transaction_type.INCOMING, date);
                                    data.setJid(message.getFrom().split("/")[0]);
                                    dbhandler.addMessage(data);
                                    dbhandler.addmsgcount(message.getFrom().split("/")[0]);
                                }
                                dbhandler.close();
                            }
                        }
                    };
                    ChatManager.getInstanceFor(connection).addChatListener(new ChatManagerListener() {
                        @Override
                        public void chatCreated(Chat chat, boolean createdLocally) {
                            chat.addMessageListener(messageListener);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SmackException e) {
                    e.printStackTrace();

                } catch (XMPPException e) {
                    e.printStackTrace();
                }

                return null;
            }
        };
        connectionThread.execute();
    }

This topic was automatically closed 62 days after the last reply. New replies are no longer allowed.