0
votes

I have created an android chat application using XMPP server (openfire) and smack lib. When open my application i get connect =>connecting than a Oncreat SMACK exception appears. Which means that i can't establish a connexion with the server my code looks right but i cant figure out where is the probleme

here is the code

public class MyXMPP {
    public static ArrayList<HashMap<String, String>> usersList=new ArrayList<HashMap<String, String>>(); 

    public static boolean connected = false;
    public boolean loggedin = false;
    public static boolean isconnecting = false;
    public static boolean isToasted = true;
    private boolean chat_created = false;
    private String serverAddress;
    public static XMPPTCPConnection connection;
    public static String loginUser;
    public static String passwordUser;

    Gson gson;
    MyService context;
    public static MyXMPP instance = null;
    public static boolean instanceCreated = false;

    public MyXMPP(MyService context, String serverAdress, String logiUser,
                  String passwordser) {
        this.serverAddress = serverAdress;
        this.loginUser = logiUser;
        this.passwordUser = passwordser;
        this.context = context;
        init();

    }

    public static MyXMPP getInstance(MyService context,String server,
                                     String user,String pass) {

        if (instance == null) {
            instance = new MyXMPP(context,server,user,pass);
            instanceCreated = true;
        }
        return instance;

    }

    public org.jivesoftware.smack.chat.Chat Mychat;

    ChatManagerListenerImpl mChatManagerListener;
    MMessageListener mMessageListener;

    String text = "";
    String mMessage = "", mReceiver = "";
    static {
        try {
            Class.forName("org.jivesoftware.smack.ReconnectionManager");
        } catch (ClassNotFoundException ex) {
            // problem loading reconnection manager
        }
    }

    public void init() {
        gson = new Gson();
        mMessageListener = new MMessageListener(context);
        mChatManagerListener = new ChatManagerListenerImpl();
        initialiseConnection();
    }



    private void initialiseConnection() {

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        config.setServiceName("farah-pc");
        config.setHost("farah-pc");
        config.setPort(5222);
        config.setDebuggerEnabled(true);
        XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        connection = new XMPPTCPConnection(config.build());

        XMPPConnectionListener connectionListener = new XMPPConnectionListener();
        connection.addConnectionListener(connectionListener);

    }


    public void connect(final String caller) {

        AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected synchronized Boolean doInBackground(Void... arg0) {
                if (connection.isConnected())
                    return false;
                isconnecting = true;
                if (isToasted)
                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(context, caller + "=>connecting....", Toast.LENGTH_LONG).show();
                        }
                    });
                Log.d("Connect() Function", caller + "=>connecting....");

                try {
                    connection.connect();
                    DeliveryReceiptManager dm = DeliveryReceiptManager
                            .getInstanceFor(connection);
                    dm.setAutoReceiptMode(AutoReceiptMode.always);

                    dm.addReceiptReceivedListener(new ReceiptReceivedListener() {

                        @Override
                        public void onReceiptReceived(final String fromid, final String toid, final String msgid, final Stanza packet) {
                        }
                    });
                    Toast.makeText( context,"cava", Toast.LENGTH_SHORT).show();

                    connected = true;

                } catch (IOException e) {
                    if (isToasted)
                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText( context,"(" + caller + ")" + "IOException: ", Toast.LENGTH_SHORT).show();
                                    }
                                });

                    Log.e("(" + caller + ")", "IOException: " + e.getMessage());
                } catch (SmackException e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.e("(" + caller + ")","SMACKException: " + e.getMessage());
                } catch (XMPPException e) {
                    if (isToasted)
                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {

                                    @Override
                                    public void run() {
                                        Toast.makeText( context,"(" + caller + ")" + "XMPPException: ", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    Log.e("connect(" + caller + ")", "XMPPException: " + e.getMessage());
                }
                return isconnecting = false;
            }
        };
        connectionThread.execute();
    }

    public void login() {

        try {
            connection.login(loginUser,passwordUser);
            Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
        } catch (XMPPException | SmackException | IOException e) {
            e.printStackTrace();
           // SmackException.ConnectionException.getFailedAddresses() ;
            //HostAddress.getException();
            Toast.makeText( context,"alaaach", Toast.LENGTH_SHORT).show();


        } catch (Exception e) {
        }

    }

    private class ChatManagerListenerImpl implements ChatManagerListener {
        @Override
        public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
                                final boolean createdLocally) {
            if (!createdLocally)
                chat.addMessageListener(mMessageListener);
        }

    }

    public void sendMessage(ChatMessage chatMessage) {

        if (!chat_created) {
            Mychat = ChatManager.getInstanceFor(connection).createChat(
                    chatMessage.receiver + "@"
                            + context.getString(R.string.server),
                    mMessageListener);
            chat_created = true;
        }
        final Message message = new Message();
        message.setBody(chatMessage.getBody());
        message.setType(Message.Type.normal);

        try {
            //if (connection.isAuthenticated()) {
                Mychat.sendMessage(message);
            //} else {
                login();
            //}
        } catch (NotConnectedException e) {
            Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
            Toast.makeText( context,"not sending", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class XMPPConnectionListener implements ConnectionListener {
        @Override
        public void connected(final XMPPConnection connection) {
            Log.d("xmpp", "Connected!");
            connected = true;
            if (!connection.isAuthenticated()) {
                login();
            }
        }

        @Override
        public void connectionClosed() {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(context, "ConnectionCLosed!",
                                Toast.LENGTH_SHORT).show();

                    }
                });
            Log.d("xmpp", "ConnectionCLosed!");
            connected = false;
            chat_created = false;
            loggedin = false;
        }

        @Override
        public void connectionClosedOnError(Exception arg0) {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(context, "ConnectionClosedOn Error!!",
                                Toast.LENGTH_SHORT).show();

                    }
                });
            Log.d("xmpp", "ConnectionClosedOn Error!");
            connected = false;

            chat_created = false;
            loggedin = false;
        }

        @Override
        public void reconnectingIn(int arg0) {

            Log.d("xmpp", "Reconnectingin " + arg0);

            loggedin = false;
        }

        @Override
        public void reconnectionFailed(Exception arg0) {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {

                        Toast.makeText(context, "ReconnectionFailed!",
                                Toast.LENGTH_SHORT).show();

                    }
                });
            Log.d("xmpp", "ReconnectionFailed!");
            connected = false;

            chat_created = false;
            loggedin = false;
        }

        @Override
        public void reconnectionSuccessful() {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(context, "REConnected!",
                                Toast.LENGTH_SHORT).show();

                    }
                });
            Log.d("xmpp", "ReconnectionSuccessful");
            connected = true;

            chat_created = false;
            loggedin = false;
        }

        @Override
        public void authenticated(XMPPConnection arg0, boolean arg1) {
            Log.d("xmpp", "Authenticated!");
            loggedin = true;
            ChatManager.getInstanceFor(connection).addChatListener(
                    mChatManagerListener);

            chat_created = false;
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }).start();
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        Toast.makeText(context, "Connected!",
                                Toast.LENGTH_SHORT).show();

                    }
                });
        }
    }

    private class MMessageListener implements ChatMessageListener {

        public MMessageListener(Context contxt) {
        }

        @Override
        public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
                                   final Message message) {
            Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
                    + message);

            System.out.println("Body-----"+message.getBody());

            if (message.getType() == Message.Type.chat
                    && message.getBody() != null) {
                final ChatMessage chatMessage = new ChatMessage();
                chatMessage.setBody(message.getBody());

                processMessage(chatMessage);
            }
        }

        private void processMessage(final ChatMessage chatMessage) {

            chatMessage.isMine = false;
            Chats.chatlist.add(chatMessage);
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    Chats.chatAdapter.notifyDataSetChanged();

                }
            });
        }

    }
}
1
can you once go through my sample github.com/saveendhiman/XMPPSample_StudioSaveen
thank you for your code great job, i tried to manage it but i am confused about ip adress to put in variables HOST and HOST1 in order to communicate 2 phones @Saveenfif
Host and host1 is server name and other is ipSaveen
So, try to make it same bothSaveen
hey @Saveen i am using openfire server so i put HOST1 = "myserver_name" and HOST=getIp() but it doesnt work how can i connect with th serverfif

1 Answers

-1
votes
//connect to server
private class MyOpenfireLoginTask extends AsyncTask<String, String, String> {
    private Context mContext;
    String username, password;
    ProgressDialog dialog;


    public MyOpenfireLoginTask(Context context) {
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(mContext);
        dialog.setMessage(getResources().getString(R.string.loading_txt));
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        username = params[0];
        password = params[1];

        Log.e("Login using ", username + " , " + password);
        Config.config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword(username, password)
                .setHost(Config.openfire_host_server_IP)
                .setResource(Config.openfire_host_server_RESOURCE)
                .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                .setServiceName(Config.openfire_host_server_SERVICE)
                .setPort(Config.openfire_host_server_CHAT_PORT)
                .setDebuggerEnabled(true)
                .build();
        Config.conn1 = new XMPPTCPConnection(Config.config);

        Config.conn1.setPacketReplyTimeout(5000);
        try {
            Config.conn1.connect();
            if (Config.conn1.isConnected()) {
                Log.w("app", "conn done");

            }
            Config.conn1.login();


            if (Config.conn1.isAuthenticated()) {
                Log.w("app", "Auth done");

            } else {
                Log.e("User Not Authenticated", "Needs to Update Password");

            }

        } catch (Exception e) {
            Log.w("app", e.toString());
        }

        return "";
    }

    @Override
    protected void onPostExecute(String result) {


        dialog.dismiss();

        if (Config.conn1.isAuthenticated()) {
            setUserPresence(0);

            //store data in session
            sharedPreferenceManager.setUsername(username);
            sharedPreferenceManager.setUserPsw(password);


            if (UserListActivity.mActivity != null) {
                UserListActivity.mActivity.finish();
            }
            Intent intent = new Intent(mContext, HomeActivity.class);
            mContext.startActivity(intent);

            if (LoginActivity.mActivity != null) {
                LoginActivity.mActivity.finish();
            }
            if (SignupActivity.mActivity != null) {
                SignupActivity.mActivity.finish();
            }
            finish();

        } else {
            Log.e(TAG, "username password wrong");
            CommonUtils.commonToast(mContext, mContext.getResources().getString(R.string.invalid_uname_psw));

            //  CommonUtils.commonToast(mContext,mContext.getResources().getString(R.string.loading_txt));
        }
    }
}

// check connection is available or not !if not redirect to login screen. public boolean isUserConnectedToServer(Activity mActivity) {

    if (Config.conn1 != null && Config.conn1.isConnected()) {
        Log.e(TAG, "----->Connected");
        setUserPresence(0);
        return true;
    } else {
        Log.e(TAG, "----->Not connected");
        setUserPresence(5);

        if (LoginActivity.mActivity != null) {
            LoginActivity.mActivity.finish();
        }
        Intent intent = new Intent(mActivity, LoginActivity.class);
        mActivity.startActivity(intent);
        mActivity.finish();

        return false;
    }

}

//disconnect user from server public void logoutUser(Activity mActivity) {

    if (Config.conn1 != null && Config.conn1.isConnected()) {
        Log.e(TAG, "-----isConnected------Logout");
        setUserPresence(5);
        Config.conn1.disconnect();

    } else {
        Log.e(TAG, "-----disconnect-------Not connected");
    }

    sharedPreferenceManager.clearData();
    //stop background service
    stopBackgroundService(mActivity);

    if (LoginActivity.mActivity != null) {
        LoginActivity.mActivity.finish();
    }
    Intent intent = new Intent(mActivity, LoginActivity.class);
    mActivity.startActivity(intent);
    mActivity.finish();
}