Update and retrieve chat history in smack with openfire -Android - android

I am making a chat application with smack library and openfire as a server but everytime i exit the chat conversation activity between two users and come back, the whole chat gets erased. I have already enabled archive settings to store one to one messages in the server but i do not know how to implement it in the app.
I want to show chats history in recyclerview by the sender and the receiver in the recyclerview.
currently i have implemented this function which caused error
private void setChatHistory(String entityBareId) {
EntityBareJid jid = null;
try {
jid = JidCreate.entityBareFrom(entityBareId);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
MamManager manager = MamManager.getInstanceFor(mConnection);
MamManager.MamQueryResult r = null;
try {
try {
r = manager.mostRecentPage(jid, 10);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
if (r.forwardedMessages.size() >= 1) //printing first of them
{
Message message = (Message) r.forwardedMessages.get(0).getForwardedStanza();
Log.i("mam", "message received" + message.getBody());
MessagesData data = new MessagesData("send",message.getBody());
mMessagesData.add(data);
mAdapter = new ConversationAdapter(mMessagesData);
recyclerView.setAdapter(mAdapter);
}
}
Error was
Attempt to read from field 'java.util.List org.jivesoftware.smackx.mam.MamManager$MamQueryResult.forwardedMessages' on a null object reference
At r.forwardedmessages.size()>=1.
Thanks in advance

If you want to keep history of conversation, you must save them in database. MAM just for fetching old conversation from server like when you uninstall or logout the app and decide to reinstall and get old messages.
For getting messages from server be sure you already enabled it, then forwarded messages shouldnt be null. here is a guide to enable it.

Related

How to properly resolve conflict during azure synchronization from android?

I'm in trouble with azure synchronization, I'm able to detect the number of pending operations by mCLient.getSyncContext().getPendingOperations(); but can't resolve them. Any help or suggestion?
When working with in an offline scenario and you have pending operations, you can push them to the server by using the push() function.
It would look something like the following:
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
// here you would do a pull on any table you want to grab data from
}
catch (final MobileServiceConflictException e)
{
// the server item causing the exception can be obtained by calling e.getItem()
JsonObject serverObject = e.getItem();
// on the sync context, call one of the following:
// .cancelAndDiscardItem() to cancel update and discard local item
// .cancelAndUpdateItem() to update the local item with the server's copy
// .cancelAndUpdateItem(JsonObject item) to update the server's item w/ the local
// make sure to call push() again on the sync context
}
All in all - make sure you call push() on the MobileServiceSyncContext and then handle any MobileServiceConflictException that may return.
If I catch for MobileServiceConflictException android studio tells me that the Exception is never thrown in this corresponding try block.
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (MobileServiceConflictException e) {
}

how to get chat history from xmpp server smack library

I want to get chat history for one to one chat and group chat. after some research i came to know that i can do it by Message Archive Management . but it does not provide any example to get older message in to android client. i want to get older message chat history from server, but i dont know how to pull older messages from xmpp server. there are so many questions asked about this over here but didn't get any proper solution. what i have done till now is connection and sending message to other user. can anyone help me to get history of chat from xmpp server?
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("user1", "password")
.setHost(getString(R.string.domain))
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(getString(R.string.domain))
.setPort(5222)
.setDebuggerEnabled(true) // to view what's happening in detail
.build();
XMPPTCPConnection conn1 = new XMPPTCPConnection(config);
conn1.setUseStreamManagement(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
conn1.setUseStreamManagementResumption(true);
// ReconnectionManager.getInstanceFor(this.conn1).enableAutomaticReconnection();
conn1.setPacketReplyTimeout(10000);
try {
conn1.connect();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
ChatManager chatmanager = ChatManager.getInstanceFor(conn1);
Chat newChat = chatmanager.createChat("user2#"+getString(R.string.domain));
try {
newChat.sendMessage("Test Msg from user1!!!");
}
catch (SmackException.NotConnectedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'd use Smack's MamManager. For example MamManager.queryArchive(Integer).

Openfire Android PubSub Subscription request aproval

I am new to Openfire and smack, therefore I have questions regarding pubsub feature. Actually, I have created a node with setAccessModel as authorize, shown below.
PubSubManager mgr = new PubSubManager(xmpp.getConnection());
try {
LeafNode leaf = mgr.createNode("testNode");
ConfigureForm form = new ConfigureForm(DataForm.Type.submit);
form.setAccessModel(AccessModel.authorize);
form.setDeliverPayloads(true);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
leaf.sendConfigurationForm(form);
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
My question is that when somebody wants to subscribe to above node, how the owner of this node can handle the subscription request? Subscription part is as follows:
PubSubManager mgr = new PubSubManager(xmpp.getConnection());
// Get the node
LeafNode node = null;
try {
node = mgr.getNode("testNode");
node.addItemEventListener(new ItemEventCoordinator());
node.subscribe(senderUser+"#desi.loc");
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
class ItemEventCoordinator implements ItemEventListener {
#Override
public void handlePublishedItems(ItemPublishEvent items) {
final ItemPublishEvent itemstemp=items;
runOnUiThread(new Runnable() {
#Override
public void run() {
//stuff that updates ui
dspySub.setText("Item: " + itemstemp.getItems());
}
});
}
}
When I set form.setAccessModel(AccessModel.open) every thing works fine. Users can publish and subscribe easily but when its AccessModel is authorize, owner don't listen, or might be I don't know how to handle subscription request at owner side with above piece of code. Kindly guide me.
Jawad, I've just replied another guy' question about listening subscription requests. Please take a look:
How can i listen incoming subscription request in smack openfire android
I really hope that it can help you.
Good luck!
PS.: Sorry, but I haven't enough reputation to do a comment :(

How to check if a device can join a multicast group or not?

I want to check if a device can join a certain multicast group or not. I am using the code snippet below.
The problem is I never got any exception even if the multicast group("239.253.0.1") is not available. It seems it can always join the group successfully and I can never catch any exception. When I use wireshark to capture the packets, however, there is no such igmp packets. Why?
try{
mcs = new MulticastSocket(1025);
group = InetAddress.getByName("239.253.0.1");
mcs.joinGroup(group);
Log.d(TAG,"join the group successfully"); //I can always get the successful msg
}catch(IOException e) {
e.printStackTrace();
} finally{
if(mcs != null) {
try{
mcs.leaveGroup(group);
mcs.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}

Function chatDidReceiveMessage not working Quickblox

I use this framework to create a messenger on Android and iOS.
In android I create a message and send it.
The server quickblox it comes !
I also see this message in the log of xcode... but no further response should not be, because the function - (void)chatDidReceiveMessage:(QBChatMessage *)message is break point.
What am I doing wrong?
Code for sending message(Android)
// create a message
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
chatMessage.setBody("Hi there");
chatMessage.setDateSent(new Date().getTime()/1000);
// attach a audio
QBAttachment attachment = new QBAttachment("audio");
attachment.setId(file.getId().toString());
chatMessage.addAttachment(attachment);
try {
currentChatRoom.sendMessage(chatMessage);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
Code in log XCode
2015-12-13 16:05:27.638 Messenger[462:5623] [ChatService] Message RCV: <message xmlns="jabber:client" id="566d5efb1fecfa062778dcd9" to="6804658-31081#chat.quickblox.com/A9320123-BD0A-4C80-BD81-F729D036877A" type="groupchat" from="31081_56616b87a0eb4756f2000b6d#muc.chat.quickblox.com/6919398"><body>Hi there</body><extraParams xmlns="jabber:client"><attachment type="audio" id="3173128"/><date_sent>1450011927</date_sent><save_to_history>1</save_to_history><message_id>566d5efb1fecfa062778dcd9</message_id><dialog_id>56616b87a0eb4756f2000b6d</dialog_id></extraParams><delay xmlns="urn:xmpp:delay" stamp="2015-12-13T13:05:27Z"/></message>
I don't understand((
If I am right, you send messages to chat room (not private chat), and then you should use chatRoomDidReceiveMessage:fromDialogID: instead. I faced the same problem, described in chatDidReceiveMessage: not called post.

Categories

Resources