How to implement instant messaging Application in android - android

I am working on an instant messaging android application . I have successfully implemented the chat between my application and web application .I have used compile 'io.socket:socket.io-client:0.6.2' library to implement this. But when i installed the same app on another mobile phone, device to device communication did not work. I think i am missing something here. What i have to implement in my app now. Broadcast Receiver or GCM(Google Cloud Messaging). My code is as below:
1. ChatActivity.java
public class ChatActivity extends Activity {
public static final String TAG = ChatActivity.class.getSimpleName();
EditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private MessagesListAdapter adapter;
private List<Message> listMessages;
private ListView listViewMessages;
boolean isSelf = false; // to check whether the message is owned by you or not.true means message is owned by you .
Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
{
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);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
almaChatDatabase = new AlmaChatDatabase(getApplicationContext());
loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listMessages = new ArrayList<Message>();
adapter = new MessagesListAdapter(getApplicationContext(), listMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mSocket.emit("subscribe", md5String);
message = edMessage.getText().toString().trim();
Log.e("message", message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Message(senderName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
JSONObject message = object.getJSONObject("message");
String messageReceived = message.getString("text");
Log.e("Message Received", messageReceived);
String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
}
2.Constants.java
public class Constants {
public static final String CHAT_SERVER_URL = "http://192.168.2.250:3000/";
}
Everything is working her except device to device communication. I am able to send messages from my app to web app and also receiving messages from web App. But device to device communication is not working. Please help me to fix the issue.

Related

How to know Incoming Email Message ID to get message contents

I want to get Incoming Email Message ID for get message contents. I've applied this code to listen change in message counts.
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
System.out.println("Message Count Event Fired");
}
public void messagesRemoved(MessageCountEvent e) {
System.out.println("Message Removed Event fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
System.out.println("Message Changed Event fired");
}
});
the above code works fine for IMAP server, whenever a message added or removed. But i want to know which Message has been removed or Added.
Kindly help. the full code is,
MainActivity:
String host = "imap.gmail.com";
String mailStoreType = "imap";
String username = "EmailAddress#gmail.com";
String password = "****";
CheckingMails.check(host, mailStoreType, username, password);
CheckingMails:
public class CheckingMails {
public static void check(String host, String storeType, String user,
String password) {
boolean supportsIdle = false;
IMAPFolder folder = null;
int freq = 2000;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
final javax.mail.Store store = session.getStore("imaps");
store.connect(host, user, password);
folder = (IMAPFolder) store.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
Log.d("fhjg43524318778", folder.toString());
try {
folder = (IMAPFolder) store.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
SearchTerm sender = new FromTerm(new InternetAddress("zohaibsvu#gmail.com"));
// Getting from specific email
Message[] message = folder.search(sender);
Log.d("fghjgh564", String.valueOf(message.length));
for (int i = 1; i < message.length; i++) {
Message writePart = message[i];
int id = message[i].getMessageNumber();
String from = message[i].getFrom()[0].toString();
String subject = message[i].getSubject();
Log.d("dfgh3423", "# "+id+" From "+from+", subject "+subject);
}
} catch (AddressException y) {
} catch (MessagingException u) {
}
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
public void messagesRemoved(MessageCountEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
});
// Check mail once in "freq" MILLIseconds
int freq = 2000;
boolean supportsIdle = false;
try {
if (emailFolder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) emailFolder;
f.idle();
supportsIdle = true;
}
} catch (FolderClosedException fex) {
throw fex;
} catch (MessagingException mex) {
supportsIdle = false;
}
for (; ; ) {
if (supportsIdle && emailFolder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) emailFolder;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(freq); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
emailFolder.getMessageCount();
}
}
/*
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
*/
//close the store and folder objects
// emailFolder.close(false);
// store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Message-ID is accessible via the MimeMessage.getMessageID method.
If you were really asking about the IMAP UID, that's accessible via the UIDFolder.getUID method. Cast the Folder object to UIDFolder.

How to implement Delayed Delivery (XEP-203) Smack

I am aware of DelayInformationManager class, and I know this is the class to achieve this. However, I dont know how to use it, how to specify the Jid destination, how to actually send it and so on.
Could anyone provide me a short example demonstrating its usage?
The using following you can achieve Delayed Delivery using smack lib.
Send Delayed Delivery Receipt
public void sendReceipt(String toJID, String sender, final String stanzaID, final String id, final long millis, Message.Type msgType) {
if(isConnected()){
Message ack = null; //2017-11-17T15:21:50.063+00:00
try {
String fromJidGroup = toJID;
if(msgType == Message.Type.groupchat){
fromJidGroup = ActivityHelper.createJid(sender) ;
}else{
fromJidGroup = toJID;
}
ack = new Message(JidCreate.from(fromJidGroup), Message.Type.chat); //msgType
ack.addExtension(new DeliveryReceipt(id));
} catch (XmppStringprepException e) {
e.printStackTrace();
}
if(millis!=0) {
DelayInformation delay = new DelayInformation(new Date(millis));
ack.addExtension(delay);
}
if(stanzaID!=null){
ack.setStanzaId(stanzaID);
}
try {
if(connection.isSmEnabled() && connection!=null) {
//addStanzaIdAcknowledgedListener send successfully Receipt or not in server
connection.addStanzaIdAcknowledgedListener(ack.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException {
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
}
connection.sendStanza(ack);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException | StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
}
Receive Delayed Delivery , First register ReceiptReceivedListener with xmpp connection
private ReceiptReceivedListener mReceiptReceivedListener;
mReceiptReceivedListener = new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(Jid from, Jid to, String rec_id, Stanza stanza) {
if(registerXmppListener!=null) {
Log.d("onReceipt","onReceipt stanza : " + stanza.toXML());
registerXmppListener.onDeliveryStatusReceived(from.toString(),to.toString(),rec_id,stanza);
}
}
};
mDeliveryReceiptManager.addReceiptReceivedListener(mReceiptReceivedListener);
onDeliveryStatusReceived Listener
public void changeMessageDeliveryStatus(String from, String to, String rec_id, Stanza stanza){
if(stanza instanceof Message) {
Message msg = (Message) stanza;
String jid = "";
if(msg.getType().equals(Message.Type.chat)){
jid = ActivityHelper.getBareJID(from);
}else if(msg.getType().equals(Message.Type.groupchat)){
jid = ActivityHelper.getSenderFromGroup(from);
}
String sender="";
long date = System.currentTimeMillis();
String stanza_id=stanza.getStanzaId();
int chat_type = 0;
int isPrivate = ChatConstants.ISPRIVATE_NO;
DelayInformation timestamp = (DelayInformation)msg.getExtension("delay", "urn:xmpp:delay");
if (timestamp == null)
timestamp = (DelayInformation)msg.getExtension("x", "jabber:x:delay");
if (timestamp != null)
date = timestamp.getStamp().getTime();
}
}

Message is displayed two times after using notifyDataSetChanged

I am working on an instant chat application.My problem is that when i am sending message through my chat application,Message is displayed two times instead of one.Screen shot is given below :
As you can see in the acreenshot that the message hiii is displayed two times but i have sent only once.
1.Adapter_Message.java
public class Adapter_Message extends BaseAdapter {
private Context context;
private List<Bean_Message> messagesItems;
public Adapter_Message(Context context, List<Bean_Message> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Bean_Message m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// Identifying the message owner
if (messagesItems.get(position).isSelf()) {
// message belongs to you, so load the right aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_right, null);
} else {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_left, null);
}
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
txtMsg.setText(m.getMessage());
lblFrom.setText(m.getFromName());
return convertView;
}
}
2.Chat_Activity.java
public class ChatActivity extends FragmentActivity implements
EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener {
public static final String TAG = ChatActivity.class.getSimpleName();
// EditText edMessage;
EmojiconEditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
//AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private Adapter_Message adapter;
private List<Bean_Message> listBeanMessages;
private ListView listViewMessages;
boolean isSelf; // to check whether the message is owned by you or not.true means message is owned by you .
Bean_Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
SharedPreferences preferences;
HashMap<String, Integer> emoticons;
// instance initialization block
{
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);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
preferences = getApplicationContext().getSharedPreferences(Prefs_Registration.prefsName, Context.MODE_PRIVATE);
//Handling emoticons
/* emoticons = new HashMap<String,Integer>();
emoticons.put(":-)",R.drawable.s1);*/
String id = preferences.getString(Prefs_Registration.get_user_id, null);
// Converting String id to integer
loggedInUserID = Integer.parseInt(id);
//loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listBeanMessages = new ArrayList<Bean_Message>();
adapter = new Adapter_Message(getApplicationContext(), listBeanMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = preferences.getString(Prefs_Registration.get_user_name, null);
//loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EmojiconEditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = edMessage.getText().toString().trim();
Log.e("Sending", "Sending data-----" + message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
setEmojiconFragment(false);
}
/* public Spannable getSmiledText(String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
if (emoticons.size() > 0) {
int index;
for (index = 0; index < builder.length(); index++) {
if (Character.toString(builder.charAt(index)).equals(":")) {
for (Map.Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
builder.setSpan(new ImageSpan(getApplicationContext(), entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
}
}
return builder;
}*/
private void setEmojiconFragment(boolean useSystemDefault) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.emojicons, EmojiconsFragment.newInstance(useSystemDefault))
.commit();
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Bean_Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
// JSONObject message = object.getJSONObject("message");
String messageReceived = object.getString("message");
Log.e("Bean_Message Received", messageReceived);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
// Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
#Override
public void onEmojiconBackspaceClicked(View view) {
EmojiconsFragment.backspace(edMessage);
}
#Override
public void onEmojiconClicked(Emojicon emojicon) {
EmojiconsFragment.input(edMessage, emojicon);
}
}
3.Bean_Message.java
public class Bean_Message {
private String fromName, message;
private boolean isSelf; // isSelf is used to check whether the message is owned by you or not
public Bean_Message() {
}
public Bean_Message(String fromName, String message, boolean isSelf) {
this.fromName = fromName;
this.message = message;
this.isSelf = isSelf;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSelf() {
return isSelf;
}
public void setSelf(boolean isSelf) {
this.isSelf = isSelf;
}
}
On clicking "Send Message" button ,message is sent to he server and the following code is used:
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
Message is stored in the Bean and Bean is added in the ArrayList .Now i am notifying my adapter that the ArrayList is updated using adapter.notifyDataSetChanged() method.But the problem is List view is displaying my sent message two times.Please help me to solve the issue .

Quickblox android sdk groupchat

I'm using quickblox sdk group chat.
This is my code. But I still wrong. Can anybody guide me, please?
UserListForGroupActivity.java
public class UserListForGroupActivity extends Activity implements QBCallback {
private ListView usersList;
private ProgressDialog progressDialog;
private Button btnChat;
private SimpleAdapter usersAdapter;
private ArrayList<Friend_Users> friends= new ArrayList<Friend_Users>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_group);
usersList = (ListView) findViewById(R.id.usersList);
btnChat=(Button)findViewById(R.id.btnstartGroupChat);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading fiends list");
progressDialog.show();
// ================= QuickBlox ===== Step 4 =================
// Get all users of QB application.
QBUsers.getUsers(this);
}
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
if (progressDialog != null) {
progressDialog.dismiss();
}
// Cast 'result' to specific result class QBUserPagedResult.
QBUserPagedResult pagedResult = (QBUserPagedResult) result;
final ArrayList<QBUser> users = pagedResult.getUsers();
System.out.println(users.toString());
// Prepare users list for simple adapter.
ArrayList<Map<String, String>> usersListForAdapter = new ArrayList<Map<String, String>>();
for (QBUser u : users) {
Map<String, String> umap = new HashMap<String, String>();
umap.put("userLogin", u.getLogin());
umap.put("chatLogin", QBChat.getChatLoginFull(u));
usersListForAdapter.add(umap);
}
// Put users list into adapter.
usersAdapter = new SimpleAdapter(this, usersListForAdapter,
android.R.layout.simple_list_item_multiple_choice,
new String[]{"userLogin", "chatLogin"},
new int[]{android.R.id.text1, android.R.id.text2});
usersList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
usersList.setAdapter(usersAdapter);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checked= usersList.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
{
QBUser friendUser = users.get(position);
String login, password;
int id;
id=friendUser.getId();
login=friendUser.getLogin();
password=friendUser.getPassword();
friends.add(new Friend_Users(id,login, password));
}
}
Friend_Users_Wrapper wrapper= new Friend_Users_Wrapper(friends);
Log.e("UserListForGroupAcitvity friend list pass intent=>", friends.size()+ friends.get(0).getLogin());
Bundle extras = getIntent().getExtras();
Intent intent=new Intent(UserListForGroupActivity.this, GroupChatActivity.class);
intent.putExtra("friends", wrapper);
intent.putExtras(extras);
startActivity(intent);
}
});
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
"please. Errors: " + result.getErrors()).create().show();
}
}
#Override
public void onComplete(Result result, Object context) { }
}
GroupChatActivity.java
public class GroupChatActivity extends Activity {
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
private QBUser me;
private GroupChatController groupChatController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
// Load QBUser objects from bundle (passed from previous activity).
Bundle extras = getIntent().getExtras();
Friend_Users_Wrapper wrapper= (Friend_Users_Wrapper) getIntent().getSerializableExtra("friends");
ArrayList<Friend_Users> friendArray= wrapper.getFriend_Users();
me = new QBUser();
me.setId(extras.getInt("myId"));
me.setLogin(extras.getString("myLogin"));
me.setPassword(extras.getString("myPassword"));
System.out.println("user login =>"+extras.getString("myLogin"));
QBUser friends= new QBUser();
for (Friend_Users friend_Users : friendArray) {
friends.setId(friend_Users.getId());
friends.setLogin(friend_Users.getLogin());
friends.setPassword(friend_Users.getPassword());
}
// UI stuff
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
sendMessageButton.setOnClickListener(onSendMessageClickListener);
messageText = (EditText) findViewById(R.id.messageEdit);
// ================= QuickBlox ===== Step 5 =================
// Get chat login based on QuickBlox user account.
// Note, that to start chat you should use only short login,
// that looks like '17744-1028' (<qb_user_id>-<qb_app_id>).
String chatLogin = QBChat.getChatLoginShort(me);
// Our current (me) user's password.
String password = me.getPassword();
if (me != null && friends != null) {
// ================= QuickBlox ===== Step 6 =================
// All chat logic can be implemented by yourself using
// ASMACK library (https://github.com/Flowdalic/asmack/downloads)
// -- Android wrapper for Java XMPP library (http://www.igniterealtime.org/projects/smack/).
groupChatController = new GroupChatController(chatLogin, password);
groupChatController.setOnMessageReceivedListener(onMessageReceivedListener);
// ================= QuickBlox ===== Step 7 =================
// Get friend's login based on QuickBlox user account.
// Note, that for your companion you should use full chat login,
// that looks like '17792-1028#chat.quickblox.com' (<qb_user_id>-<qb_app_id>#chat.quickblox.com).
// Don't use short login, it
String friendLogin = QBChat.getChatLoginFull(friends);
groupChatController.startChat(friendLogin);
}
}
private void sendMessage() {
if (messageText != null) {
String messageString = messageText.getText().toString();
groupChatController.sendMessage(messageString);
messageText.setText("");
showMessage(me.getLogin() + " (me) : "+messageString, true);
}
}
private GroupChatController.OnMessageReceivedListener onMessageReceivedListener = new GroupChatController.OnMessageReceivedListener() {
#Override
public void onMessageReceived(final Message message) {
String messageString = message.getBody();
showMessage(messageString, false);
}
};
private void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(GroupChatActivity.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
};
}
GroupChatController.java
public class GroupChatController {
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
// Multi-User Chat
private MultiUserChat muc2;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public GroupChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
muc2 = new MultiUserChat(connection, "2389_chat1#muc.chat.quickblox.com");
// Discover whether user3#host.org supports MUC or not
// The room service will decide the amount of history to send
muc2.join(chatLogin);
muc2.invite(friendLogin, "Welcome!");
Log.d("friendLogin ->",friendLogin);
// Set listener for outcoming messages.
//chatManager.addChatListener(chatManagerListener);
muc2.addMessageListener(packetListener);
addListenerToMuc(muc2);
//chat1#muc.chat.quickblox.com
}
Message message = new Message(friendLogin + "#muc.chat.quickblox.com");
message.setBody("Join me for a group chat!");
message.addExtension(new GroupChatInvitation("2389_chat1#muc.chat.quickblox.com"));
connection.sendPacket(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
/*** muc */
private void addListenerToMuc(MultiUserChat muc){
if(null != muc){
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Log.i("processPacket", "receiving message");
}
});
}
}
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message)packet;
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
//System.out.println("got message " + message.toXML());
}
};
private PacketInterceptor packetInterceptor = new PacketInterceptor() {
#Override
public void interceptPacket(Packet packet) {
System.out.println("Sending message: " + packet.toString());
Message message = muc2.createMessage();
message.setBody("Hello from producer, message " +
" ");
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/***/
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
// Set listener for incoming messages.
chat.addMessageListener(messageListener);
muc2.addMessageListener(packetListener);
}
};
public void sendMessage(String message) {
try {
if (chat != null) {
chat.sendMessage(message);
}
if (muc2 != null) {
muc2.sendMessage(message);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
private MessageListener messageListener = new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
// 'from' and 'to' fields contains senders ids, e.g.
// 17792-1028#chat.quickblox.com/mac-167
// 17744-1028#chat.quickblox.com/Smack
String from = message.getFrom().split("#")[0];
String to = message.getTo().split("#")[0];
System.out.println(String.format(">>> Message received (from=%s, to=%s): %s",
from, to, message.getBody()));
if (onMessageReceivedListener != null) {
onMessageReceivedListener.onMessageReceived(message);
}
}
};
public static interface OnMessageReceivedListener {
void onMessageReceived(Message message);
}
// Callback that performs when device retrieves incoming message.
private OnMessageReceivedListener onMessageReceivedListener;
public OnMessageReceivedListener getOnMessageReceivedListener() {
return onMessageReceivedListener;
}
public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
this.onMessageReceivedListener = onMessageReceivedListener;
}
}
public void startChat(String buddyLogin) {
...
List<String> usersLogins= new ArrayList<String>();
for(String userLogin: usersLogins){
muc2.invite(userLogin, "Welcome!");
}
...
}

Having a bit of trouble tcp connecting in Android Client

This might be a complex problem with my application but I'll do my best to describe it as accurately as I can.
I am making an Android Client and making use of a couple of helper classes someone else handed to me at work. The helper Android classes are called TcpClient.java and PVDCAndroidClient.java. PVDCAndroidClient.java makes use out of the TcpCLient, using a tcpCLient object to connect via serverIP and port.
Here is PVDCAndroidClient.java:
public class PVDCAndroidClient {
// constants
public static final String DEFAULT_LOGIN_URI = "http://me.net:8000/";
private TcpClient tcpClient = null;
private UdpClient udpClient = null;
private boolean connected = false;
private boolean loggedin = false;
private static SimpleDateFormat sdf;
private String loginURI = DEFAULT_LOGIN_URI;
private int getUserNumber;
TcpMessageListener listener = null;
/**
* Connects to proxy server, blocks until complete or timeout
* #param serverIP
* #param port
*/
public void connect(String serverIP, int port)
{
try
{
if(serverIP.length() != 0 && port != 0)
{
tcpClient = new TcpClient();
tcpClient.addTcpListener(listener);
tcpClient.connect(serverIP, port);
}
}
catch(Exception e)
{
e.printStackTrace();
Log.d("Could not connect to server, possbile timeout...", "error");
}
}
///// Make login function a blocking call
// Default login, use last location as login location
public boolean login(String fName, String lName, String password)
{
return this.login(fName, lName, password, "last location");
}
public boolean login(String fName, String lName, String password, String region)
{
return this.login(fName, lName, password, "last location", 128, 128, 20);
}
public boolean login(String fName, String lName, String password, String region, int loginX, int loginY, int loginZ)
{ sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Check passed values
// x, y and z should be between [0, 256]
// strings should not be null or empty(except lName which can be empty)
if((loginX >= 0 && loginX <= 256) && (loginY >=0 && loginY <= 256) && (loginZ >= 0 && loginZ <= 256))
{
if(fName.length() != 0 && fName != null)
{
// Construct packet xml structure
// Send request and wait until reply or timeout
// return false if timeout (or throw exception?)
// if not timeout, read result packet and determine return value
// getUserNumber = tcpClient.getUserNum();
StringWriter stringWriter = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(stringWriter);
// Indentation is not required, but helps with reading
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
// TODO: Remove hardcoding of strings, make either constants or place in strings.xml
// TODO: Move the header construction to other method as it is fairly constant other than request num and no need to repeat that much code
serializer.startTag("", "pvdc_pkt");
serializer.startTag("", "pvdc_header");
// TODO: replace this with a string unique to the system
serializer.startTag("", "ID");
serializer.text("838393djdjdjd");
serializer.endTag("", "ID");
// TODO: replace this with actual user number from server
serializer.startTag("", "user_num");
serializer.text("22");//get userNum from above
serializer.endTag("", "user_num");
// TODO: add a request number counter to increment this on each request
serializer.startTag("", "request_num");
serializer.text("1");
serializer.endTag("", "request_num");
serializer.startTag("", "DateTime");
serializer.text(sdf.toString()); //utc time variable.
serializer.endTag("", "DateTime");
serializer.endTag("", "pvdc_header");
serializer.startTag("", "pvdc_content");
serializer.attribute("", "type", "requestlogin");
serializer.startTag("", "name");
serializer.attribute("", "fname", fName);
serializer.attribute("", "lname", lName);
serializer.endTag("", "name");
serializer.startTag("", "password");
serializer.text(password);
serializer.endTag("", "password");
serializer.startTag("", "server");
serializer.text(this.loginURI);
serializer.endTag("", "server");
serializer.startTag("", "location");
serializer.attribute("", "region", region);
serializer.text(loginX + ";" + loginY +";" + loginZ);
serializer.endTag("", "location");
serializer.endTag("", "pvdc_content");
serializer.endTag("", "pvdc_pkt");
// Finish writing
serializer.endDocument();
// write xml data out
serializer.flush();
//
sendLogin(stringWriter);
} catch (Exception e) {
Log.e("Exception", "error occurred while creating xml file");
return false;
}
// Print out xml for debugging
Log.d("PVDCAndroidClient Login", stringWriter.toString().trim());
}
else
{
Log.d("Error in name checking", "fName either blank or null");
}
}
else
{
Log.d("login coordinates X,Y, or Z not between 0-256", "Coordinates Error");
}
return true;
}
// moveString should contain the properly formatted movement command(s)[see above move request description]
public void sendLogin(StringWriter stringWriter)
{
tcpClient.sendMessage(stringWriter.toString());
}
}
Here is the actual TcpClient.java:
public class TcpClient {
public interface TcpMessageListener{
public void onMessage(TcpClient client, String message);
}
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private Thread listenThread = null;
private boolean listening = false;
private int userNum = -1;
private List<TcpMessageListener> listeners = new ArrayList<TcpMessageListener>();
public int getUserNum()
{
return this.userNum;
}
public TcpClient() {
}
public void addTcpListener(TcpMessageListener listener)
{
synchronized(this.listeners)
{
this.listeners.add(listener);
}
}
public void removeTcpListener(TcpMessageListener listener)
{
synchronized(this.listeners)
{
this.listeners.remove(listener);
}
}
public boolean connect(String serverIpOrHost, int port) {
try {
socket = new Socket(serverIpOrHost, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.listenThread = new Thread(new Runnable(){
public void run() {
int charsRead = 0;
char[] buff = new char[4096];
while(listening && charsRead >= 0)
{
try {
charsRead = in.read(buff);
if(charsRead > 0)
{
Log.d("TCPClient",new String(buff).trim());
String input = new String(buff).trim();
synchronized(listeners)
{
for(TcpMessageListener l : listeners){
l.onMessage(TcpClient.this, input);
}
}
if (input.toLowerCase().contains("<user_num>")){
int index = input.toLowerCase().indexOf("<user_num>");
index += "<user_num>".length();
int index2 = input.toLowerCase().indexOf("</user_num>");
userNum = Integer.parseInt(input.substring(index, index2));
}
}
} catch (IOException e) {
Log.e("TCPClient", "IOException while reading input stream");
listening = false;
}
}
}
});
this.listening = true;
this.listenThread.setDaemon(true);
this.listenThread.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
return false;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
return false;
} catch (Exception e) {
System.err.println(e.getMessage().toString());
return false;
}
return true;
}
public void sendMessage(String msg) {
if(out != null)
{
out.println(msg);
out.flush();
}
}
public void disconnect() {
try {
if(out != null){
out.close();
out = null;
}
if(in != null){
in.close();
in = null;
}
if (socket != null) {
socket.close();
socket = null;
}
if(this.listenThread != null){
this.listening = false;
this.listenThread.interrupt();
}
this.userNum = -1;
} catch (IOException ioe) {
System.err.println("I/O error in closing connection.");
}
}
}
LASTLY, here is what I have been coding today and cannot seem to get this to work. I don't get any blatant exceptions, just a warning on Logcat, that says, "Couldn't get I/O for the connection".
public class AndroidClientCompnt extends Activity {
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptPassLoginActivity;
private String getIpAddressSharedPrefs;
private String getPassword, getName, getRegionSelect, getGridSelect;
private String fName, lName;
private SharedPreferences settings;
private boolean resultCheck = false;
private int portNum;
PVDCAndroidClient client;
private String name;
private CharSequence[] getView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Intent intent = getIntent();
// getting object's properties from LoginActivity class.
getName = intent.getStringExtra("name");
getPassword = intent.getStringExtra("password");
getRegionSelect = intent.getStringExtra("regionSelect");
getGridSelect = intent.getStringExtra("gridSelect");
Log.d("VARIABLES", "getName = " + getName + "getPassword" + getPassword
+ "getRegionSelect = " + getRegionSelect + ".");
setResult(Activity.RESULT_CANCELED);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
// grid selected as well? sometime?
settings = PreferenceManager.getDefaultSharedPreferences(this);
getIpAddressSharedPrefs = settings.getString(IP_ADDRESS_SHARED_PREFS,
"");
portNum = Integer.parseInt(settings.getString(PORT_SHARED_PREFS, ""));
Log.d("SHARED" + getIpAddressSharedPrefs + "port " + portNum, "");
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
try {
// first connect attempt.
client.connect(getIpAddressSharedPrefs, portNum);
resultCheck = client.isConnected();
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not connect.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Ip preference and port blank", Toast.LENGTH_LONG).show();
}
finish();
}
private class UploadTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
// encrypting user's password with Md5Hash class.
try {
encryptPassLoginActivity = MdHashing
.MD5(getPassword.toString());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (resultCheck == true) {
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = name.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,
getRegionSelect, 128, 128, 20);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent goToInWorld = new Intent(
AndroidClientCompnt.this.getApplicationContext(),
PocketVDCActivity.class);
startActivity(goToInWorld);
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
I know this is a super long post and I am asking a lot but if anyone could take a look at this I would very much appreciate it. I've been at this all day, trying to make use of these helper classes I got and can't get it to work. It also doesn't help that I'm not too experienced in this client/server stuff. Any nudges in the right direction or an accepted solution would REALLY mean something to me.
Thank you kindly,
Have a good evening.
Can you post your manifest?
You may need to add the following :
<uses-permission android:name="android.permission.INTERNET"/>
Additionally - I assume you see nothing ever happen on the server side of this connection?
1) Make sure you have the following permission in your Android-Manifest file:
<uses-permission android:name="android.permission.INTERNET/>
w/o this you definitely won't be making any tcp/ip connections.
2) You will want to run the code in debug mode, and place breakpoints where the connection information
is set and also what results are at several points. In other words you need to dig deeper.
If you are somewhat new to coding there is no better investment of time than in running the debugger and stepping line by line through the code. Code only comes to life inside a debugger, where you can see the values of variables and results. So set several breakpoints, step through and you will see more. It is more difficult to debug where there are threads however.

Categories

Resources