title: Convert String to XMPP Stanza using Smack Android
body: <p>or </p>
  
  <ul>
  <li><p><strong>Q) Generate XMPP Stanza From String.</strong></p></li>
  <li><p><strong>Q) Cast String into XMPP Stanza.</strong></p></li>
  </ul>
  
  <p>By using Smack library in Android,</p>
  
  <pre><code>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 ---&gt;", msgString);
  </code></pre>
  
  <p>the above code generated following stanza</p>
  
  <p><strong>msgString:</strong></p>
  
  <pre><code>&lt;message from='923442621149' id='123' type='chat'&gt;&lt;body&gt;shanraisshan&lt;/body&gt;&lt;/message&gt;
  </code></pre>
  
  <p>I have save this <strong><em>msgString</em></strong> into my database.</p>
  
  <p>Now, What I wanted to do is, on retrieving this string back from database</p>
  
  <ul>
  <li>Cast this <strong><em>msgString</em></strong> back into Java <strong><em>Message</em></strong> Class</li>
  <li>so that I can use attributes (<strong><em>From, Body, Id</em></strong>)</li>
  <li>using <strong><em>message.getFrom()</em></strong></li>
  </ul>
  
  <hr>
  
  <p>Since <strong><em>Message</em></strong> is a child class of <strong><em>Stanza</em></strong>, I tried the below code:</p>
  
  <pre><code>Stanza stanza = new Stanza() {
      @Override
      public CharSequence toXML() {
          return msgString;
      }
  };
  Log.e("stanza XML ---&gt;", stanza.toXML().toString());
  Log.e("stanza getFrom() -&gt;", stanza.getFrom() + ":");
  Log.e("stanza getStanzaId() -&gt;", stanza.getStanzaId() + ":");
  </code></pre>
  
  <p>The Console Log prints follows</p>
  
  <pre><code>stanza XML ---&gt;: &lt;message from='923442621149' id='123' type='chat'&gt;&lt;body&gt;shanraisshan&lt;/body&gt;&lt;/message&gt;
  stanza getFrom() -&gt;: null:
  stanza getStanzaId() -&gt;: OtU0i-29:
  </code></pre>
  
  <p>I am unable to understand, why </p>
  
  <ul>
  <li><p>stanza.toXML().toString() prints the right stanza while</p></li>
  <li><p>stanza.getFrom() is <strong><em>null</em></strong> instead of <strong><em>923442621149</em></strong></p></li>
  <li><p>stanza.getStanzaId() is <strong><em>OtU0i-29</em></strong> instead of <strong><em>123</em></strong></p></li>
  </ul>
  
  <hr>
  
  <p>Plus, on casting Stanza to Message , produces <strong>ClassCastException</strong></p>
  
  <pre><code>Message castedMsg = (Message)stanza;
  </code></pre>
  
  <p>produces</p>
  
  <pre><code>java.lang.ClassCastException:
  </code></pre>
  
  <hr>
  
  <h2><strong>SIMPLIFYING THINGS</strong></h2>
  
  <p>How can I convert <strong>msgString</strong></p>
  
  <pre><code>msgString = "&lt;message from='923442621149' id='123' type='chat'&gt;&lt;body&gt;shanraisshan&lt;/body&gt;&lt;/message&gt;";
  </code></pre>
  
  <p>into org.jivesoftware.smack.packet.<strong>Message</strong> class?</p>