RecyclerView: No adapter attached; skipping layout with android socket io - android

i am trying to make an android realtime chat using node js server and socket.io this is the chatbox activity :
public class ChatBoxActivity extends AppCompatActivity {
public RecyclerView myRecylerView ;
public List<Message> MessageList ;
public ChatBoxAdapter chatBoxAdapter;
public EditText messagetxt ;
public Button send ;
//declare socket object
private Socket socket;
public String Nickname ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_box);
messagetxt = (EditText) findViewById(R.id.message) ;
send = (Button)findViewById(R.id.send);
// get the nickame of the user
Nickname= (String)getIntent().getExtras().getString(MainActivity.NICKNAME);
//connect you socket client to the server
try {
socket = IO.socket("http://10.0.2.2:3000");
socket.connect();
socket.emit("join", Nickname);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//setting up recyler
MessageList = new ArrayList<>();
myRecylerView = (RecyclerView) findViewById(R.id.messagelist);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
myRecylerView.setLayoutManager(mLayoutManager);
myRecylerView.setItemAnimator(new DefaultItemAnimator());
// message send action
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//retrieve the nickname and the message content and fire the event messagedetection
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("messagedetection",Nickname,"jfjdjfj");
messagetxt.setText(" ");
}
}
});
//implementing socket listeners
socket.on("userjoinedthechat", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("userdisconnect", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
// make instance of message
Message m = new Message(nickname,message);
//add the message to the messageList
MessageList.add(m);
// add the new updated list to the dapter
chatBoxAdapter = new ChatBoxAdapter(MessageList);
// notify the adapter to update the recycler view
chatBoxAdapter.notifyDataSetChanged();
//set the adapter for the recycler view
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
this is node js server code :
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('CHAT' , function (data) {
console.log('======CHAT message========== ');
console.log(data);
socket.emit('CHAT',data);
});
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
});
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})
details about the error :
the server is running correctly it's printing 'server listening on port 3000' in the console . also when i join the chat the socket 'join' and 'disconnect' are emmitted since i get this in my console log:
one user connected xVs1-xYtvNA5sd-dAAAA
one user disconnected xVs1-xYtvNA5sd-dAAAA
only the connect and disconnect socket events are emitted but the send and recevie messages aren't being emitted .

You just need to give the recyclerView an adapter at the same time you give it the layoutManager... It is skipping the layout here when getting the adaper
[UPDATE]
For the socket not emmiting the message on your server you are not listening for the "message" or on the android side you are not listening for the "chat" I would modify your server side code to match your android application as such
Final code:
public class ChatBoxActivity extends AppCompatActivity {
public RecyclerView myRecylerView ;
public List<Message> MessageList ;
public ChatBoxAdapter chatBoxAdapter;
public EditText messagetxt ;
public Button send ;
//declare socket object
private Socket socket;
public String Nickname ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_box);
messagetxt = (EditText) findViewById(R.id.message) ;
send = (Button)findViewById(R.id.send);
// get the nickame of the user
Nickname= (String)getIntent().getExtras().getString(MainActivity.NICKNAME);
//connect you socket client to the server
try {
socket = IO.socket("http://10.0.2.2:3000");
socket.connect();
socket.emit("join", Nickname);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//setting up recyler
MessageList = new ArrayList<>();
myRecylerView = (RecyclerView) findViewById(R.id.messagelist);
// message send action
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//retrieve the nickname and the message content and fire the event messagedetection
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("message",Nickname,"jfjdjfj");
messagetxt.setText(" ");
}
}
});
//implementing socket listeners
socket.on("userjoinedthechat", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("userdisconnect", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
// make instance of message
Message m = new Message(nickname,message);
//add the message to the messageList
MessageList.add(m);
// add the new updated list to the dapter
chatBoxAdapter = new ChatBoxAdapter(MessageList);
// notify the adapter to update the recycler view
chatBoxAdapter.notifyDataSetChanged();
//set the adapter for the recycler view
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
myRecylerView.setLayoutManager(mLayoutManager);
myRecylerView.setItemAnimator(new DefaultItemAnimator());
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('message' , function (data) {
console.log('======CHAT message========== ');
console.log(data);
socket.emit('message',data);
});
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
});
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})

Related

How to update Message Activity without refresh?

I am making app where users can chat with each other in app , but the problem is when user send message it doesn't appear in chat box until user refresh the activity . how can i update chat without refresh ?
this is my code
ParseQuery<Message> parseQuery = ParseQuery.getQuery(Message.class);
subscriptionHandling = parseLiveQueryClient.subscribe(parseQuery);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, new SubscriptionHandling.HandleEventCallback<Message>() {
#Override
public void onEvent(ParseQuery<Message> query, final Message message) {
// HANDLING create event
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mList.add(message);
msgAdapter.notifyDataSetChanged();
show_message.scrollToPosition(mList.size() - 1);
}
});
public void onEvent(ParseQuery<Message> query, Message message) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mList.clear();
getData();
}
});
public void onClick(View v) {
Message msg = parseMessenger.SendMessage(send_txt.getText().toString(), null, new SaveCallback() {
#Override
public void done(ParseException e) {
send_txt.setText("");
}
}, new SendCallback() {
#Override
public void done(ParseException e) {
}
});
if (mList == null) {
mList = new ArrayList<Message>();
}
}
});
getData();
private void getData() {
ParseQuery<Message> messageFromQuery = Message.getAllMessage();
messageFromQuery.whereEqualTo(Message.COL_USER_FROM, userFrom);
messageFromQuery.whereEqualTo(Message.COL_USER_TO, userTo);
ParseQuery<Message> messageToQuery = Message.getAllMessage();
messageToQuery.whereEqualTo(Message.COL_USER_TO, userFrom);
messageToQuery.whereEqualTo(Message.COL_USER_FROM, userTo);
List<ParseQuery<Message>> messageQueries = new ArrayList<ParseQuery<Message>>();
messageQueries.add(messageFromQuery);
messageQueries.add(messageToQuery);
ParseQuery<Message> messageQuery = ParseQuery.or(messageQueries);
messageQuery.orderByAscending("createdAt");
messageQuery.findInBackground(new FindCallback<Message>() {
#Override
public void done(List<Message> messages, ParseException e) {
if (messages != null) {
mList.clear();
mList.addAll(messages);
msgAdapter = new MsgAdapter(requireContext(), mList, userTo.getObjectId(), userTo);
show_message.setAdapter(msgAdapter);
show_message.scrollToPosition(mList.size() - 1);
}
}
});
}
i can add auto refresh when send button is clicked but i don't want so , it will not look nice when users use it .. please help

Add addMessageListener for MultiUserChat Using Smack 4.1

I'm new to android and I tried to create a chat app using Smack 4.1 and Ejabberd.
I have implemented a group chat using MultiUserChat. I have added Messagelistener to listen every new incoming message and add into adapter.
When I enter into chat room and start chat list works very well.
But the problem is when I back to the any other intent and then go back into chat room then when someone messages me, it is received multiple times.
Maybe I set messagelistner multiple times.
Here is my code Activity Class -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatiing);
user2 = getIntent().getExtras().getString("JID");
msg_edittext = (EditText)findViewById(R.id.messageEditText);
msgListView = (ListView)findViewById(R.id.msgListView);
msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatlist = new ArrayList<ChatMessage>();
chatlist.clear();
chatAdapter = new ChatAdapter(ChattingGroup.this,chatlist);
msgListView.setAdapter(chatAdapter);
autoJoinRoom(user1,room_name,new View(getApplicationContext()));
ImageButton sendButton = (ImageButton)findViewById(R.id.sendMessageButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendTextMessage(view);
}
});
}
public void autoJoinRoom(String user, String room, View view){
LoginActivity activity = new LoginActivity();
XMPPTCPConnection connection = activity.getmService().xmpp.connection;
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat multiUserChat = manager.getMultiUserChat(room);
try {
multiUserChat.join(user,"12345");
chatlist.clear();
multiUserChat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Message message) {
if(message.getBody() != null){
Log.d("New Message Received",message.getBody());
chatlist.add(message.getBody());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/* Change adapter */
((BaseAdapter) msgListView.getAdapter()).notifyDataSetChanged();
}
});
}
}
});
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
}
}
How can I solve this problem ?

Android Emitter.Listener not working

I'm making an app with socket IO, it connects correctly to the server, but it doesn't listen to events.
Here's part of my code:
private Socket mSocket;
{
try {
mSocket = IO.socket(ip+":8000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ads);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.connect();
mSocket.on("send file", onSendFile);
}
private Emitter.Listener onSendFile = new Emitter.Listener() {
#Override
public void call(Object... args) {
String data = (String) args[0];
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
mSocket.emit("fileok", "OKIDOKI");
}
};
try to show toast on UI thread instead of different thread using getActivity().runOnUiThread
private Emitter.Listener onSendFile = new Emitter.Listener() {
#Override
public void call(Object... args) {
String data = (String) args[0];
mSocket.emit("fileok", "OKIDOKI");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
});
}
};

feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas smack android

I am trying to develop a chat application but instead of Google message service I tried writing xmmp node server.
I am able to login in to server.But getting message saying feature not implemented.
<iq to='359648069251166#10.10.25.126/Smack' id='cu03M-5' type='error'><error type='cancel'><feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
android code
final TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setServiceName(IPADRESS)
.setHost(IPADRESS)
.setPort(5222)
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.setPacketReplyTimeout(1000);
SmackConfiguration.DEBUG = true;
conn2.connect();
conn2.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
}
#Override
public void connectionClosed() {
}
#Override
public void connectionClosedOnError(Exception e) {
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
#Override
public void reconnectionFailed(Exception e) {
}
});
conn2.addAsyncPacketListener(new PacketListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
if (packet != null) {
Log.d("stanza", "received" + packet.toXML());
Toast.makeText(getApplicationContext(), packet.toXML(), Toast.LENGTH_LONG).show();
}
}
}, new PacketFilter() {
#Override
public boolean accept(Stanza packet) {
return true;
}
});
Roster roster = Roster.getInstanceFor(conn2);
//Get all rosters
Collection<RosterEntry> entries = roster.getEntries();
//loop through
for (RosterEntry entry : entries) {
//example: get presence, type, mode, status
Presence entryPresence = roster.getPresence(entry.getUser());
Presence.Type userType = entryPresence.getType();
Presence.Mode mode = entryPresence.getMode();
String status = entryPresence.getStatus();
Log.d("stanza",userType+" "+status);
}
roster.addRosterListener(new RosterListener() {
#Override
public void presenceChanged(Presence presence) {
//Called when the presence of a roster entry is changed
}
#Override
public void entriesUpdated(Collection<String> arg0) {
// Called when a roster entries are updated.
}
#Override
public void entriesDeleted(Collection<String> arg0) {
// Called when a roster entries are removed.
}
#Override
public void entriesAdded(Collection<String> arg0) {
// Called when a roster entries are added.
}
});
conn2.login(mngr.getDeviceId(), "secret");
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("I’m available");
conn2.sendPacket(presence);
ChatManager chatManager = ChatManager.getInstanceFor(conn2);
Chat chat = chatManager.createChat(mngr.getDeviceId(), new ChatMessageListener() {
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
Log.d("stanza", message.toString());
// processMessage(chatMessage);
}
}
});
// Add a packet listener to get messages sent to us
Message message = new Message();
message.setFrom(mngr.getDeviceId());
message.setTo(mngr.getDeviceId());
message.setType(Message.Type.chat);
message.setSubject("jhelloworld");
chat.sendMessage(message);
}catch (Exception e){
Log.d("error",e.getMessage());
}
I took server from here.
server side code.
var startServer = function (done) {
// Sets up the server.
server = new xmpp.C2S.TCPServer({
port: 5222,
domain: 'localhost'
})
server.on('connection', function (client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
client.on('register', function (opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function (opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === 'secret') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
} else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function () {
console.log('server:', client.jid.local, 'ONLINE')
client.send("")
})
// Stanza handling
client.on('stanza', function (stanza) {
console.log('server:', client.jid.local, 'stanza', stanza.toString())
var from = stanza.attrs.from
stanza.attrs.from = stanza.attrs.to
stanza.attrs.to = from
client.send(stanza)
})
// Stanza handling
client.on('chat', function (stanza) {
console.log('server:', client.jid.local, 'chat', stanza.toString())
client.send(stanza)
});
// On Disconnect event. When a client disconnects
client.on('disconnect', function () {
console.log('server:', client.jid.local, 'DISCONNECT')
})
})
server.on('listening', done)
}
startServer(function (){
console.log("server localhost started at 5222 localport");
});
I tried many solution from stackoverflow and smack community but didnt.
help will be appreciated.

Unable to read response from server using Socket.IO client in android

I am working on an android chat application .I am not able to connect to my server using Socket.Io client in android.
1.ChatActivity.java
public class ChatActivity extends Activity {
EditText edMessage;
private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
edMessage = (EditText) findViewById(R.id.edtMessage);
String message = edMessage.getText().toString().trim();
mSocket.connect();
// mSocket.emit("subscribe", "Testing");
mSocket.on("subscribe", subscribe);
}
private Emitter.Listener subscribe = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String room = (String) args[0];
Log.e("Response", room);
}
});
}
};
}
Please help me to solve the issue.I am not able to verify whether the server is connected or not .

Categories

Resources