简体   繁体   中英

Convert String to XMPP Stanza using Smack Android

or

  • Q) Generate XMPP Stanza From String.

  • Q) Cast String into XMPP Stanza.

By using Smack library in Android,

Message message = new Message();
message.setStanzaId("123");
message.setFrom("923442621149");
message.setType(Message.Type.chat);
message.setBody("shanraisshan");

final String msgString = message.toXML().toString();
Log.e("message --->", msgString);

the above code generated following stanza

msgString:

<message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>

I have save this msgString into my database.

Now, What I wanted to do is, on retrieving this string back from database

  • Cast this msgString back into Java Message Class
  • so that I can use attributes ( From, Body, Id )
  • using message.getFrom()

Since Message is a child class of Stanza , I tried the below code:

Stanza stanza = new Stanza() {
    @Override
    public CharSequence toXML() {
        return msgString;
    }
};
Log.e("stanza XML --->", stanza.toXML().toString());
Log.e("stanza getFrom() ->", stanza.getFrom() + ":");
Log.e("stanza getStanzaId() ->", stanza.getStanzaId() + ":");

The Console Log prints follows

stanza XML --->: <message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>
stanza getFrom() ->: null:
stanza getStanzaId() ->: OtU0i-29:

I am unable to understand, why

  • stanza.toXML().toString() prints the right stanza while

  • stanza.getFrom() is null instead of 923442621149

  • stanza.getStanzaId() is OtU0i-29 instead of 123


Plus, on casting Stanza to Message , produces ClassCastException

Message castedMsg = (Message)stanza;

produces

java.lang.ClassCastException:

SIMPLIFYING THINGS

How can I convert msgString

msgString = "<message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>";

into org.jivesoftware.smack.packet. Message class?

After going through Smack Library source code on Github , I found out that the library is using PacketParserUtils.java method's parseStanza() for casting String to Stanza.

String  msgString = "<message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>";
Message message = (Message)PacketParserUtils.parseStanza(msgString);

Log.e("message XML->", message.toXML().toString());
Log.e("message getFrom()->", message.getFrom() + ":"); //923442621149:
Log.e("message getStanzaId()->", message.getStanzaId() + ":"); //123:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM