Building your own android chat messenger app similar to Whatsapp using XMPP (Smack 4.1 API) from scratch: Part-2

By | August 26, 2015
Android Chat tutorial

Android Chat tutorial




In Part-1 we finished the implementation of chat interface for our android messenger. Now we will focus on implementing the client for XMPP server to send & receive chat messages using Smack API for Android.

Adding library files to the project:

Download the library files for Smack API and GSON which is a library for converting java objects to JSON strings.

– Copy the jar files into the libs folder of your android project. If this folder does not exists then create it.

– Right click on the jar files, go to Build Path -> Add to Build Path. Repeat this step for each .jar file in the libs folder.

Adding third party libraries:

– Download this file and extract it to the src folder of your project directory. This step will add new packages along with your existing packages in the src directory. These packages are required by smack library as third party libraries.

Now we have successfully added all the required library files to our android project.

Create a new java file named MyXMPP.java in your com.marothiatechs.mchat package in src folder.

We will write the implementation of smack library in this file and will use this file to initialise connections to XMPP server and also to send and receive chat messages.

The content of the MyXMPP.java goes as follows:

package com.marothiatechs.mchat;

import java.io.IOException;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager.AutoReceiptMode;
import org.jivesoftware.smackx.receipts.ReceiptReceivedListener;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.marothiatechs.fragments.Chats;

public class MyXMPP {

 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(serverAddress);
  config.setHost(serverAddress);
  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 disconnect() {
  new Thread(new Runnable() {
   @Override
   public void run() {
    connection.disconnect();
   }
  }).start();
 }

 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) {

      }
     });
     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();
  } 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) {
  String body = gson.toJson(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(body);
  message.setStanzaId(chatMessage.msgid);
  message.setType(Message.Type.chat);

  try {
   if (connection.isAuthenticated()) {

    Mychat.sendMessage(message);

   } else {

    login();
   }
  } catch (NotConnectedException e) {
   Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");

  } catch (Exception e) {
   Log.e("xmpp.SendMessage()-Exception",
     "msg Not sent!" + e.getMessage());
  }

 }

 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() {
      // TODO Auto-generated method stub

      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() {
      // TODO Auto-generated method stub

      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);

   if (message.getType() == Message.Type.chat
     && message.getBody() != null) {
    final ChatMessage chatMessage = gson.fromJson(
      message.getBody(), ChatMessage.class);

    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();

    }
   });
  }

 }
}

As you can see in the source code, we have created methods for initialising, connecting, sending messages as well as a listener for processing received messages.

In android long running processes has to be implemented in background. So we will use Android Service for our requirements.

Creating Android Service:

Create a file named LocalBinder.java and copy the below contents:

package com.marothiatechs.mchat;

import java.lang.ref.WeakReference;
import android.os.Binder;

public class LocalBinder<S> extends Binder {
 private final WeakReference<S> mService;

 public LocalBinder(final S service) {
  mService = new WeakReference<S>(service);
 }

 public S getService() {
  return mService.get();
 }

}

Now save this file into the package com.marothiatechs.mchat in src directory.

Create another file name MyService.java and copy the code :

package com.marothiatechs.mchat;

import org.jivesoftware.smack.chat.Chat;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.IBinder;

public class MyService extends Service {
 private static final String DOMAIN = "xmpp.jp";
 private static final String USERNAME = "khushi";
 private static final String PASSWORD = "password";
 public static ConnectivityManager cm;
 public static MyXMPP xmpp;
 public static boolean ServerchatCreated = false;
 String text = "";


 @Override
 public IBinder onBind(final Intent intent) {
  return new LocalBinder<MyService>(this);
 }

 public Chat chat;

 @Override
 public void onCreate() {
  super.onCreate();
  cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  xmpp = MyXMPP.getInstance(MyService.this, DOMAIN, USERNAME, PASSWORD);
  xmpp.connect("onCreate");
 }

 @Override
 public int onStartCommand(final Intent intent, final int flags,
   final int startId) {
  return Service.START_NOT_STICKY;
 }

 @Override
 public boolean onUnbind(final Intent intent) {
  return super.onUnbind(intent);
 }

 @Override
 public void onDestroy() {
  super.onDestroy();
  xmpp.connection.disconnect();
 }

 public static boolean isNetworkConnected() {
  return cm.getActiveNetworkInfo() != null;
 }
}

MyService.java is the class for android service and it will be running in the background. You can learn more about services here.

Now modify the contents of our MainActivity.java to this:

package com.marothiatechs.mchat;

import java.util.Locale;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.marothiatechs.fragments.Chats;

public class MainActivity extends ActionBarActivity implements
  ActionBar.TabListener {

 private static final String TAG = "MainActivity";
 private boolean mBounded;
 SectionsPagerAdapter mSectionsPagerAdapter;
 ViewPager mViewPager;
 private MyService mService;
 private final ServiceConnection mConnection = new ServiceConnection() {

  @SuppressWarnings("unchecked")
  @Override
  public void onServiceConnected(final ComponentName name,
    final IBinder service) {
   mService = ((LocalBinder<MyService>) service).getService();
   mBounded = true;
   Log.d(TAG, "onServiceConnected");
  }

  @Override
  public void onServiceDisconnected(final ComponentName name) {
   mService = null;
   mBounded = false;
   Log.d(TAG, "onServiceDisconnected");
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  doBindService();

  final ActionBar actionBar = getSupportActionBar();
  actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

  mSectionsPagerAdapter = new SectionsPagerAdapter(
    getSupportFragmentManager());

  mViewPager = (ViewPager) findViewById(R.id.pager);
  mViewPager.setAdapter(mSectionsPagerAdapter);

  mViewPager
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
     @Override
     public void onPageSelected(int position) {
      actionBar.setSelectedNavigationItem(position);
     }
    });

  // For each of the sections in the app, add a tab to the action bar.
  for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

   actionBar.addTab(actionBar.newTab()
     .setText(mSectionsPagerAdapter.getPageTitle(i))
     .setTabListener(this));
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

  int id = item.getItemId();
  if (id == R.id.action_settings) {
   return true;
  }
  return super.onOptionsItemSelected(item);
 }

 @Override
 public void onTabSelected(ActionBar.Tab tab,
   FragmentTransaction fragmentTransaction) {

  mViewPager.setCurrentItem(tab.getPosition());
 }

 @Override
 public void onTabUnselected(ActionBar.Tab tab,
   FragmentTransaction fragmentTransaction) {
 }

 @Override
 public void onTabReselected(ActionBar.Tab tab,
   FragmentTransaction fragmentTransaction) {
 }

 public class SectionsPagerAdapter extends FragmentPagerAdapter {

  public SectionsPagerAdapter(FragmentManager fm) {
   super(fm);
  }

  @Override
  public Fragment getItem(int position) {
   if (position == 1) {
    return new Chats();
   } else
    return PlaceholderFragment.newInstance(position + 1);
  }

  @Override
  public int getCount() {
   // Show 3 total pages.
   return 3;
  }

  @Override
  public CharSequence getPageTitle(int position) {
   Locale l = Locale.getDefault();
   switch (position) {
   case 0:
    return getString(R.string.title_section1).toUpperCase(l);
   case 1:
    return getString(R.string.title_section2).toUpperCase(l);
   case 2:
    return getString(R.string.title_section3).toUpperCase(l);
   }
   return null;
  }
 }

 public static class PlaceholderFragment extends Fragment {

  private static final String ARG_SECTION_NUMBER = "section_number";

  public static PlaceholderFragment newInstance(int sectionNumber) {
   PlaceholderFragment fragment = new PlaceholderFragment();
   Bundle args = new Bundle();
   args.putInt(ARG_SECTION_NUMBER, sectionNumber);
   fragment.setArguments(args);
   return fragment;
  }

  public PlaceholderFragment() {
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   View rootView = inflater.inflate(R.layout.fragment_main, container,
     false);
   return rootView;
  }
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  doUnbindService();
 }

 void doBindService() {
  bindService(new Intent(this, MyService.class), mConnection,
    Context.BIND_AUTO_CREATE);
 }

 void doUnbindService() {
  if (mConnection != null) {
   unbindService(mConnection);
  }
 }

 public MyService getmService() {
  return mService;
 }

}

Now as we have implemented android service and  connection to xmpp server is done inside the service, we have to use our implementation to send messages using xmpp class instead of simply adding an entry to the listview in the chat_layout.xml of Chats.java

So modify the sendTextMessage() method in Chats.java in package com.marothiatechs.fragments to send messages using xmpp.
So the final code for Chats.java will be :

package com.marothiatechs.fragments;

import java.util.ArrayList;
import java.util.Random;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.marothiatechs.mchat.ChatAdapter;
import com.marothiatechs.mchat.ChatMessage;
import com.marothiatechs.mchat.CommonMethods;
import com.marothiatechs.mchat.MainActivity;
import com.marothiatechs.mchat.R;

public class Chats extends Fragment implements OnClickListener {

 private EditText msg_edittext;
 private String user1 = "khushi", user2 = "khushi";// chating with self
 private Random random;
 public static ArrayList<ChatMessage> chatlist;
 public static ChatAdapter chatAdapter;
 ListView msgListView;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.chat_layout, container, false);
  random = new Random();
  ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(
    "Chats");
  msg_edittext = (EditText) view.findViewById(R.id.messageEditText);
  msgListView = (ListView) view.findViewById(R.id.msgListView);
  ImageButton sendButton = (ImageButton) view
    .findViewById(R.id.sendMessageButton);
  sendButton.setOnClickListener(this);

  // ----Set autoscroll of listview when a new message arrives----//
  msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
  msgListView.setStackFromBottom(true);

  chatlist = new ArrayList<ChatMessage>();
  chatAdapter = new ChatAdapter(getActivity(), chatlist);
  msgListView.setAdapter(chatAdapter);
  return view;
 }

 @Override
 public void onSaveInstanceState(Bundle outState) {
 }

 public void sendTextMessage(View v) {
  String message = msg_edittext.getEditableText().toString();
  if (!message.equalsIgnoreCase("")) {
   final ChatMessage chatMessage = new ChatMessage(user1, user2,
     message, "" + random.nextInt(1000), true);
   chatMessage.setMsgID();
   chatMessage.body = message;
   chatMessage.Date = CommonMethods.getCurrentDate();
   chatMessage.Time = CommonMethods.getCurrentTime();
   msg_edittext.setText("");
   chatAdapter.add(chatMessage);
   chatAdapter.notifyDataSetChanged();
   MainActivity activity = ((MainActivity) getActivity());
   activity.getmService().xmpp.sendMessage(chatMessage);
  }
 }

 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  case R.id.sendMessageButton:
   sendTextMessage(v);

  }
 }

}

Now the java coding part is done and we need to modify our AndroidManifest.xml file  to add certain permissions and to declare MyService.

So the modified AndroidManifest.xml is :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.marothiatechs.mchat"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

  <service
            android:name=".MyService"
            android:enabled="true" />
        </application>

</manifest>




The final project hierarchy should look like this:

Now run the application and go to Chats tab.
Try to send any message and it will come back to you because we are sending it to ourself i.e we used same username for both sender and receiver in our code.

The screenshot for the running app:

Simply change the user2 variable in Chats.java to other username if you want to chat with other users.

It was just a simple app to show the implementation of Smack 4.1 API in android. You can further modify the project according to your needs to develop a fully functional messenger.

You can download a demo apk file of the tutorial here.

191,100 total views, 7 views today

(Visited 154,282 times, 16 visits today)
  • Pingback: Building your own android chat messenger app similar to Whatsapp using XMPP (Smack 4.1 API) from scratch: Part-1 | TutorialsFace()

  • Pingback: Building your own android chat messenger app similar to Whatsapp using XMPP (Smack 4.1 API) from scratch: Part-1 - TutorialsFace()

  • chief

    Wow thanks i lot for this great tutorial. i followed everything so well getting all the intricacies well. i have just a little problem with the file MYXMPP in the line + context.getString(R.string.server), the problem is am not sure what the server(uderlined) references to, what string is that because it also affects some exception. am new to android and programing but am catching up/ thx

    • Laxman Marothiya

      context.getString(R.string.server) refers to “xmpp.jp” located in /res/values/strings.xml

      It is the name of the domain where your xmpp server is located. xmpp.jp is a public XMPP Server.

      • chief

        } catch (Exception e) {
        Log.e(“xmpp.SendMessage()-Exception”,
        “msg Not sent!” + e.getMessage());
        }

        BUt Still i have the above exception code underlined in red in the file Myxmpp.java. Same file where the server error was. what is the cause, as during runtime my app crashes when sending a message… thx in advance

        • Laxman Marothiya

          Are you using the same username and password that is provided in the code?

          • chief

            yes
            private static final String DOMAIN = “xmpp.jp”;
            private static final String USERNAME = “khushi”;
            private static final String PASSWORD = “password”;

          • chief

            could i send u a copy of what ive been working on so can spot what am doing wrong..can i send u an email>? could u pliz share yo email

          • Laxman Marothiya
          • chief

            sent

          • chief

            i like extend my thanks for your guidance towards understanding how xmpp works using this tutorial as a newbie. i read a great deal to get it all. i always appreciate this spirited guidance, thanks again

          • Chandan kumar

            Hi, I am not able to chat with different users even I change the user2 value. Did you face it or any idea on it ?

    • Harsh D. Sharma

      please share the tutorial to me also.my ID is harsh.dayal027@gmail.com

  • http://edusagar.com Pankaj Pal

    Thanks a lot for this – A complete solution.

    • Laxman Marothiya

      😉

      • http://edusagar.com Pankaj Pal

        I had a small query – what if i want to keep my processMessage inside service instead of xmpp.java . How to do that ? Basically, i am thinking that xmpp.java shouldnt be worried about processing of messages, it should just act as an interface so that we can provide our own custom handler.

      • Rahul Hooda

        I am getting “ConnectionClosedOn Error!”. After debugging found it in the connection listener. Struggling from this from over 3 days now. I tried with your demo apk but it is working fine. I followed this tutorial step by step and everything is well placed at its place. Please help…

      • chathuragune

        I am getting:

        “Attempt to invoke.interface method ‘byte[] org.jivessoftware.smack.util.stringencoder.Base64$Encoder.encode(byte[], int, int) on a null object reference.'”
        in this method:

        Fails in this login() in MyXMPP.java.

        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(); */
        } catch (Exception e) {
        mytoast(“login failed ” + ” loginUser= “+ loginUser + ” passwordUser=”+ passwordUser+ ” ” + e.toString());
        }

        }

        • Chandan kumar

          Hi, Did you fix this issue ? If yes please let me know what I need to change in code?

        • Rahul Matte

          I am facing same issue, please share the solution if you found

        • Viral Patel

          I am also facing same issue, please share the solution if you found

          • Дамир Каримов

            Did you solved this error? I have the same error too.

        • Дамир Каримов

          Hi!
          Did you solved this error? I have the same error too.

        • Amit Leshem

          Hi, have anyone solved this issue?

  • Devendra Singh

    Hi laxman, i followed your both but yet i am not able to receive the message. the message only being added to adapter and showing in listview but msgs aren’t receiving. plus the Fragment isn’t showing the view. please suggest me what should i do. if you want to share my code i will on your mail id(Commented below) please reply ASAP. either you can mail me on droidwithme@gmail.com or whatsapp me on 9799990168.

    • Tushar Narang

      did you solve it ?

      • Devendra Singh

        yes i done that.

        • Tushar Narang

          Can you please share your version of the Source Code ?
          tushar.nrng@gmail.com

          • Tushar Narang

            Atleast let me know what did I miss

          • Devendra Singh

            you don’t need to write the fragment. just create two activities. see the part 1 to create Interface. add the chat fragment’s code in to the new activity. and copy all the classes as it is. build it.
            i am out of the home. this evening i will send mine code.

          • Sidh

            Can you share your source code to hitssidh@gmail.com, as i am facing the same issue, my openfire is also configured. Thanks in advance 🙂

          • Devendra Singh

            i will mail you in evening.

          • Sidh

            hey sorry to bother you but didn’t get your mail 😐 can you send once again ?

          • Devendra Singh

            I shared the drive link. just now again,

          • Android Dotsquares

            Dervendra Sir,
            Can you please share your version of the Source Code ?
            mail id is ajayaswal.bwm@gmail.com

          • sayali

            Hi,

            Can you send me too? Please I am having issues with this part since a long time.
            sayali.0710@gmail.com

          • Harsha Cheemakurthy

            Hello 🙂

            Can you please share the source code with me. My email address is harsha00711@gmail.com

            Many Many Thanks!

          • Vipin Sivaraman

            Hi…We planned to have a simple android chat application for our final year engineering project. Could you please share the source code , it will be of great help.
            Vipin.S
            vips83@gmail.com

          • Rodrigo Lapenda

            Dervendra Sir,

            Can you please share the Source Code ?

            mail id is rlapenda@gmail.com

            thanks in advance.

          • Harsha Cheemakurthy

            Hello Devendra Sir 🙂

            Can you please share the source code with me. My email address is harsha00711@gmail.com

            Many Many Thanks!
            Harsha

          • Saurabh Sharma

            Hello Devendra,

            Could you also send me the drive link? My email id is: Saurabh713@gmail.com. I would greatly appreciate your help. Thanks in advance. 🙂

            Saurabh

          • Akshay

            please share with me too..
            akshaybasotra@gmail.com
            thanks.

          • Chandan kumar

            Hi Devendra, I am also not able to receive messages. Can you please help me on it? Or If possible please share code on my email id : chandan.km07@gmail.com

          • Devendra Singh

            got the mail?

          • chathuragune

            Hi, can you email me the working project code at chathuragune at gmail.com. Many thanks!

          • Saurabh Sharma

            Hello Sidh,

            If you have the source, Could you also send me the drive link? My email id is: Saurabh713@gmail.com.

            Thanks,
            Saurabh

      • Devendra Singh

        tell me your mail i will send the whole code. you can send image also. i assume you have configured your openfire. if not do that first.

        • kuks Roid

          Hi,

          Can you share the working source code @ saurabhkukreja@live.com

          Or share the google drive link here , which will be useful for everyone

          • Devendra Singh

            sorry for delay, actually i was out of station. soon i will post the working code.

      • kuks Roid

        Hi Tushar,
        Can you share the working source code @ saurabhkukreja@live.com
        Or share the google drive link here , which will be useful for everyone

  • Ara Gevorgyan

    Thanks, for nice article.
    But I’m getting an error that says:
    “Connection closed with error org.jivesoftware.smack.SmackException: Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element”

    This happens in a couple of seconds after running the app.
    Why could this happen?

    • es

      did you fix the problem ? cause i have the same problem and i cant find how to fix it
      thank you

    • Avishek Das

      I got the same problem Laxman. Please help me.

    • Avishek Das

      Hey Ara Gevorgyan did you solve the problem??

  • Hersi

    public MMessageListener(Context contxt) is this right or should it be
    public MMessageListener(Context context) ? great tutorial i wonder if we can do same on android studio.

  • Khizer Aziz

    Hello there Sir Laxman,

    Thank You so very much for such a great tutorial. I have not seen a single tutorial and teacher like this. Perfect. Glad to find your site… You are Great…

    I have followed all your instructions step by step, but getting problem here in MyXMPP.

    no further progress after initializing “config”.

    private void initialiseConnection() {

    Log.d(“tag”, ” before initializing config”);
    XMPPTCPConnectionConfiguration.Builder config =XMPPTCPConnectionConfiguration.builder();
    Log.d(“tag”, ” after initializing config”);

    config.setSecurityMode(
    ConnectionConfiguration.SecurityMode.disabled);
    config.setServiceName(serverAddress);
    config.setHost(serverAddress);
    config.setPort(5222);
    config.setDebuggerEnabled(true);

    XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
    XMPPTCPConnection.setUseStreamManagementDefault(true);

    connection = new XMPPTCPConnection(config.build());

    XMPPConnectionListener connectionListener = new XMPPConnectionListener();
    connection.addConnectionListener(connectionListener);
    }//end

    LogCat Comments:

    11-23 20:08:22.390 28463-28463/com.marothiatechs.myapplication D/tag: before initializing config

    Actually i am just a beginner to android. tried hard to find some solution but couldn’t….

    Would be very thankful if you can help out with this problem..
    Thanks ind advance.
    Screenshot attached.

    • Khizer Aziz

      i sorted out things. it was my libraries… i updated them to smack 4.1.5
      now they work like charm. still thanks brother.

  • rishabh agarwal

    Hey, I am getting a nullPointerException at this line:
    activity.getmService().xmpp.sendMessage(chatMessage);

    Any help would be appreciated.Thanks.

  • Nikhil Singh

    Hi,
    This tutorial is excellent but I am facing one issue.

    I am able to send the message but it is not coming as reply from receiver, however I am using sender and receiver same ID.

    What could the the possible reason for this issue.

  • Sachin Suryavanshi

    My app crashes at activity.getmService().xmpp.sendMessage(chatMessage); I am also having problem with R.string.server..can u tell me the exact flow and solution of this.Please help me asap because I am working on this.I was able to do part-1 and not able to run app successfully in part-2

    • Dominika K

      Did you solve your problem with R.string.server?? I have problem with it too. Cannot resolve symobl ‘server’ 🙁

  • Juan Martin Buireo

    Hi, thanks for this tutorial. It helped me a lot with my project.

    I have one doubt. I am using OpenFire as server with smack. I made the connection and it’s working perfect. But I tried to go one step ahead an implemented a login.

    So, as I’m using OpenFire, I want to do the login against this server. I could manage to make this work, but as the service and the xmpp instance are made in background I don’t know when they really finished connecting.

    I need that in the login once I click on the button login the execution freezes until the xmpp is connected and authenticated so that the user gets a feedback is the authentication was correct or not. How can I do this?

    Thanks

    • Rohan

      use a BroadcastReceiver, maybe ?

    • Nikhil Borad

      got success with openfire server or not ??

    • Nikhil Borad

      does this work with openfire..?

      • Steve Drumble

        Yeap, it works with Openfire

    • Steve Drumble

      That’s for you add ConnectionListener. If you added it and after running you app you do have “connceted” in the logcat then you are free to login.

    • Mihir Gadkari

      are u able to send and receive messages. i am getting the 404 error. remote server not found

      • Mihir Gadkari

        Just changed the server value in strings.xml to domain name instead of IP address and the issue got resolved

    • Muhammad Afzal

      you can do it by implementing XMPP gick API

  • Bugra Onucyildiz

    “ConnectionClosedOn Error!” Please help… bonucyildiz@gmail.com send project pls

    • Karla Nikitenko

      Do you receive code? I have the same problem if work fine or someone sharer with pliss send to me karlinhanikitenko@gmail.com

  • Karla Nikitenko

    Can you share your source code to I have any problems pliss someone send me a work code sent to karlinhanikitenko@gmail.com Thanks Karla Nikitenko

  • Bugra Onucyildiz

    Hello I succeeded, I tried to add to your project the next server features add to my library in the following Links

    http://mvnrepository.com/artifact/org.igniterealtime.smack/smack-java7/4.1.0-rc2

    Server Info

    Server IP Adress

    private static final String DOMAIN = “Server IP Adress”;

    private static final String USERNAME = “username”; sample “admin”

    private static final String PASSWORD = “deneme”;

    but for me you would make a request to the application service connection, albeit off how I keep standing bonucyildiz@gmail.com

    • Dhaval P

      can you share the source code? i am not able to finish the code

  • Anita Gomber

    java.lang.NoClassDefFoundError: com.google.gson.Gson

    • Laxman Marothiya

      You need gson jar file for your project

    • waseem ahmad

      u hv to use gson.jar in libs folder

  • Anita Gomber

    Hi, I am using same id for both sender as well as receiver but I am not able to receive msg

    • Dhaval P

      hey, i am also facing similar issue. how ever the connected Toast is also not showing.

      • Tarun Sharma

        hi, did u find solution for receiving Message because i am facing similar problem.would u please send me code on
        tarun_9689@yahoo.com

        • Mihir Gadkari

          Same issue . Getting 404 remote server not found error. Please send code to mihir.gadkari@gmail.com

        • Mihir Gadkari

          Instead of using the IP address for “server” in strings.xml, use … Server -> Server Manager -> Server Information -> Server Properties -> Server Name … from the Openfire admin console as value

          My issue of receiving messages got resolved after doing this change 🙂

    • Tarun Sharma

      hi Anita did u find solution for receiving Message because i am facing similar problem.would u please send me code on
      tarun_9689@yahoo.com

  • Anita Gomber

    please provide me some step to use this with my application as a chat functionality ,my email id is anita.gomber@gmail.com

  • Anita Gomber

    someone please share the code how configure openfire ,my email id is anita.gomber@gmail.com

    • Devendra Singh

      i,ll post soon. the updated code. and instruction.

      • Nikhil Borad

        sir.. waiting

        • Devendra Singh

          https://drive.google.com/open?id=0BxVa3_wqOp_rbGlRbVBYZjBNOEE this is working code of chat app, with storing msg, send images and get contacts. you just change the “algonation” with your pc name where openfire installed, and your ip address.

          • Nikhil Borad

            thank you sir 🙂
            how can i achieve read status in this
            an d one more how can i achieve push notification with openfire..?

    • Nikhil Borad

      hey @anitagomber:disqus Did u find with Openfire..?

  • Anusha Hansaria

    Hello, Great Tutorial.. However I am unable to receive message even though I am using the same user for both. Could you please help me with this? I am really stuck..

  • Maneesh Kumar Gaud

    hello sir!
    chatadapter java class show error for arraylist&it and chatmessage&gt and chatMessageList…

    can u solve this prblm…

    • saif

      “&lt” replace with lessenthan “&gt” replace with greater than

      • Maneesh Kumar Gaud

        ArrayList<ChatMessage> chatMessageList;

        public ChatAdapter(Activity activity, ArrayList<ChatMessage>list ArrayListchatlist ArrayList chatlist)
        {
        chatMessageList = list;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        i found error here…

      • Maneesh Kumar Gaud

        can u send me source code?

  • Maneesh Kumar Gaud

    unfortuinately stop….
    any idea…

  • assamba pasquier

    that is a great tutorial. congratulation. but i have one problem
    i can not process activity.getmservice().xmpp…. its return unfortunatly stop. pliz can you tell me what is the matter?

  • assamba pasquier

    please can you tell me why activity.getmService().xmpp.sendMessage doesn’t walk? it throws unfortunatly stop

  • assamba pasquier

    that is my gmail: assambapasquier@gmail.com

  • Avishek Das

    Hey Laxman

    I got this exception:
    03-28 16:55:51.007 16238-16263/com.marothiatechs.mchat W/AbstractXMPPConnection: Connection closed with error

    org.jivesoftware.smack.SmackException: Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element

    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1148)

    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)

    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)

    at java.lang.Thread.run(Thread.java:818)

    03-28 16:55:51.021 16238-16263/com.marothiatechs.mchat D/xmpp: ConnectionClosedOn Error!

    before this I got this:

    03-28 16:54:50.942 16238-16255/com.marothiatechs.mchat D/xmpp: Connected!

    So I think it is problem of authentication. Can you please help me??

    Thanks in advance.

    • kuks Roid

      Hi
      Did you solved it, I am facing the same isue

      • Avishek Das

        No I can’t. 🙁 Did you know that now xmpp server supports this or not? But I realize one thing that if it is not supports then how the demo apk works?

      • Avishek Das

        Yea I just solve it now. Remove all jar file from libs folder. And remove the third party library too. i.e org.zip(https://drive.google.com/open?id=0B2iPPSXcpjrGYmkwODRzT3FzOGM) Clean the project. Then add this

        compile(‘org.igniterealtime.smack:smack-android:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-android-extensions:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-core:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-tcp:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-extensions:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-experimental:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-resolver-minidns:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-sasl-provided:4.1.1’)

        compile(‘org.igniterealtime.smack:smack-im:4.1.1’)

        compile(‘org.jxmpp:jxmpp-core:0.4.2-beta1’)

        compile(‘org.jxmpp:jxmpp-util-cache:0.4.2-beta1’)

        compile(‘com.google.code.gson:gson:2.3.1’)

        • kuks Roid

          Thanks buddy, nailed it.
          one more thing, I am not sure, but while reading other posts on similar topic, I read so much about setting up XMPP server,
          Can you please guide, if I need to setup openfire/Ejabber and hot to configure it in our code.

          right now, I am getting below logs:
          biwsbj1za3VrcjMscj1NK0E0cTxNJjs7XypEUCpiPXdcNjRfQWd8OjF4fWBqYQ==

          03-29 10:06:12.451 10660-10941/skukr3.com.mychat D/SMACK﹕ RECV (0): cj1NK0E0cTxNJjs7XypEUCpiPXdcNjRfQWd8OjF4fWBqYXlTVWdmY1ZtalBMZi9oWnp3Y1c3bWc9PSxzPUczNWJHeGZ4djhiVitZTzNQbmpoTnc9PSxpPTQwOTY=

          03-29 10:06:12.841 10660-10940/skukr3.com.mychat D/SMACK﹕ SENT (0): Yz1iaXdzLHI9TStBNHE8TSY7O18qRFAqYj13XDY0X0FnfDoxeH1gamF5U1VnZmNWbWpQTGYvaFp6d2NXN21nPT0scD1KY0swbTFjZUt2eDNMK0taa2c0QUxzd1BvaUk9

          03-29 10:06:14.172 10660-10941/skukr3.com.mychat D/SMACK﹕ RECV (0):

          03-29 10:06:14.182 10660-10941/skukr3.com.mychat W/SASLError﹕ Could not transform string ‘bad_auth’ to SASLError

          java.lang.IllegalArgumentException: bad_auth is not a constant in org.jivesoftware.smack.sasl.SASLError

          org.jivesoftware.smack.sasl.SASLErrorException: SASLError using SCRAM-SHA-1: bad-auth

          So I guess, I am missing some server side configurations on my side.

  • Fison

    thx for this tutorial,
    please try to explain user how to config user 1 and user 2 in different devices so that we can be able to receive message, we are able only to send

    • kuks Roid

      Hi
      I am trying to run the app,
      but i am getting Smack Exception(not able to login )
      Can you please tell, what would be the value for R.String.server

  • kuks Roid

    Hi,
    Can anyone please tell, what would be the value for R.String.server

  • Devendra Singh

    Guys i am back. soon i will post the well-working code with documentation.

  • Mayank Patel

    hi plz give me the source code of this app

  • Karla Nikitenko

    Hi I need help, The connection it’s Ok but for to send the message I have problems because de message never return to the user, without displaying any error. Plis send or shared work code… or help-me karlinhanikitenko@gmail.com

  • Karla Nikitenko

    Devendra Singh Pliss shared on the comments the source code on google drive anyone don’t know how to do for received message… Pliss help us.

    • Devendra Singh

      I done. 🙂

  • Rahul Matte

    nice..i want to set up server side, How to do that,

  • eki ashadi

    can u send the source code please to ekiashadi88@gmail.com

  • Maneesh Kumar Gaud

    run time error… application unfortunatelt stop.

    FATAL EXCEPTION: main
    Process: com.example.gokulesh.chat, PID: 28097
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gokulesh.chat/com.example.gokulesh.chat.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.app.ActionBar.setNavigationMode(int)’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.app.ActionBar.setNavigationMode(int)’ on a null object reference
    at com.example.gokulesh.chat.MainActivity.onCreate(MainActivity.java:68)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

  • Atashi Roy

    Hello,Please guide me about setup chat server and app.My mail id is atashi.cse@gmail.com

  • kits abrahams

    An Error is happening on this line activity.getmService().xmpp.sendMessage in chats.java on the sendTextMessage()

    I tried to trace it and it turns out that this method in the MainActivity is not binding;
    void doBindService() {
    Log.d(“Bind”, “Binding”);
    bindService(new Intent(this, ChatService.class), mConnection,
    Context.BIND_AUTO_CREATE);
    }

    Tried this
    void doBindService() {
    Log.d(“Bind”, “Binding”);
    bolean b = bindService(new Intent(this, ChatService.class), mConnection,
    Context.BIND_AUTO_CREATE);
    Log.d(“Binding is “, b) // it returns “Binding is false”

    }

    Anyone help me to fix this issue

    • kits abrahams

      Note I named “MyService” as “ChatService”

  • kits abrahams

    This is a great tutorial. I managed to set up the server . on Ubuntu
    $ sudo apt-get install ejabberd
    $ sudo vi /etc/ejabberd/ejabberd.yml and add more hosts u want to use in my case is used the local ip of the machine i.e 192.168.*.*
    $sudo ejabberdctl register user host password
    $sudo service ejabberd start

    use one of the users you have setup respectively

  • Devendra Singh

    Hey Guys if you need this project mail me on droidwithme@gmail.com with subject “App Project”

  • sagar

    can you provide source code in android studio project or eclipse project . it would be easier to understand the code in the ide.

  • kuks Roid

    Thank you so much for sharing, the code works like charm ,
    I am facing one problem , I can authenticate using LDAP but not with custom Auth provider.
    Can anyone share any example or any help would be highly appreciated.

    Regards
    Saurabh Kukreja

  • Morris

    Hey send me the source code morryzregz100@gmail.com.
    I am having a problem with R.string.server

  • Navneet Sharma

    Hello SIr.
    thanks for this tutorial.
    i have compiled the code but now struck at one point.
    Where now i get my user name?
    please guide mw to create which server and how.
    Thank You

    • Garry Greg

      Hello Sharma, I can help you with how to create and configure the
      XMPP server. Please send me your working source code to garrygreg34@gmail.com

    • Blerim Blerii

      How did u managed this to work? i did exactly the same code but it won’t work, the toast is showing connecting and then it disappears, while i downlaoded the demo apk from this site and after that connecting toast it shows Connected. can you please help me ?

  • Aniket

    send me the source code @ aniket.narvankar@triologic.com

  • lahigma

    please can you send me a source code for this tutorial please!! this is my email :
    h.medika@yahoo.com

  • lahigma

    please any one can help me to build a very basic smack 4.1 android app also with (connect and login)

  • Carlos

    Hi from Venezuela. Great Job, send me the source code Atenciocarlos@outlook.com

  • Harsh D. Sharma

    socket time out exception has been come(client is not,or no longer,connected).please resolve issue.

  • gowthaman C

    Guys i need source pls sent me…..My email id:cgowthamanmca@gmail.com

  • Jaya Gautam

    Hi,
    I tried your code. Server is connected but i am not able to get login on this server.

    Please help.

    Thanks in advance !!!

  • Mayank

    Hey!
    You apk is doing nothing except creating tabbed activity ! Nothing happens by clicking over “Chats” tab.

  • Madhu Kalyan

    Hi i am able to login and send messages, but not able to receive messages

    I am using smack 4.1.7

    Please help me

    Thank you

  • jaffa reddy

    Its showing cannot resolve symbol for pager in MainActivity and server in MyXMPP.java.what should be done?

  • kovid

    org not a complete directory sdk shows given error..

    My E-mail- kovidkumar48@gmail.com

    • Handrata Samsul

      if you have imported all the lib using gradle, you don’t need to copy those org files..

      • http://twicekenyablog.blogspot.co.ke Peter musumbi

        grandle code should be?

    • Blerim Blerii

      If anyone sees my comment, please help me, i did this tutorial two times, but it won’t work, i downloaded the demo apk provided on this site and it works, but in the app i created there’s exactly the same code, when i launch my app, the toast shows connecting and then it disappears while on the demo apk launched on the same device it shows connecting and then connected, what’s going wrong? i don’t have any error or exceptions, please help me

      • Steve Drumble

        If you don’t have “connected” then something already has gone wrong. May be your host or server name wrong. Consider to erase all code and build it step by step(firstly connecting, after logging in and then sending messages).

        • Blerim Blerii

          I actually did step by step exactly provided, and used his domain, but it won’t work, but anyway i gave up on this i am looking forward to implement this method in the future but not now, thank you for replying btw.

  • kovid

    sdk shows given error..

  • Shailendra Rajpoot

    Hi sir your tutorial is nice I have completed first part success full in my Android studio but when I go for second part I m not understanding how to do this in my Android studio where put libs package plz send me source code of second part my email ID shailendra20rajpoot@gmail.com

    • Nikhil Borad

      Simple paste below lines in gradle.. and Sync it.

      compile(‘org.igniterealtime.smack:smack-android:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-android-extensions:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-core:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-tcp:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-extensions:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-experimental:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-resolver-minidns:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-sasl-provided:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-im:4.1.1’)
      compile(‘org.jxmpp:jxmpp-core:0.4.2-beta1’)
      compile(‘org.jxmpp:jxmpp-util-cache:0.4.2-beta1’)
      compile(‘com.google.code.gson:gson:2.3.1’)
      Hope this help…

  • Joao Eduardo Galli

    Could I have the source also? joaogalli@gmail.com

  • rohit

    hey can u send me source code at rs22891@yahoo.com
    thank you

  • Nikhil Borad

    How to implement this with openfire server.. any Help..??

    • Steve Drumble

      Just install Openfire, run it , and paste your ip as host, and server name as service name.

  • aroosh mishra

    I am new to android development. i am getting below errors. please help arooshmishra@gmail.com

    • Nikhil Borad

      Simple paste below lines in gradle.. and Sync it.

      compile(‘org.igniterealtime.smack:smack-android:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-android-extensions:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-core:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-tcp:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-extensions:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-experimental:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-resolver-minidns:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-sasl-provided:4.1.1’)
      compile(‘org.igniterealtime.smack:smack-im:4.1.1’)
      compile(‘org.jxmpp:jxmpp-core:0.4.2-beta1’)
      compile(‘org.jxmpp:jxmpp-util-cache:0.4.2-beta1’)
      compile(‘com.google.code.gson:gson:2.3.1’)
      Hope this help…

  • aroosh mishra

    can some share fragment_main.xml code pls. arooshmishra@gmail.com

  • aroosh mishra

    Please share complete code. Arooshmishra@gmail.com

  • Rajan surendar

    In MyXMPP.java class (R.string.server). What is that server?? And for what purpose that server was used?? Then how can I install that server??

    • Steve Drumble

      R.id.server is address of a server on which all information goes, like messeges, photos, videos etc. You can use Openfire or any other database(not sure if it’s database) as your server.

  • dinesh

    i have this error

    • Eloy

      Hello Dinesh, did you solve the problem?

  • Vlad Zbuker

    Good day, I have a question, how can I set message listener when the app is closed? The thing is that my app doesn’t receive messages when it’s closed, and what’s the point of a chat app that can’t notify a user when the message arrives =) Hope someone will answer me soon. And by the way thanks for the tutorial =)))

  • Sanjo Thomas

    Hi, I am a super duper newbie in android development. I am asked to develop an chat app similar to whatsapp, atleast the chatting part.
    I am stuck, I am getting an error while running the application .
    “onCreate:Connecting…..”

    then this messsage pops up
    “onCreate:SMASHException” .

    then
    Connection closed shows up

    I followed step by step, still getting the error.
    Is there any additional step that I have to take care. like
    1) do I need to change the username or password or server address?
    2) do i need an open fire account?

    Please help me out!

  • Akshay Sudhakaran

    can you give the whole project as zip?

  • Sanjo Thomas

    mail me the code at thomasanjo@gmail.com

  • Akhilesh

    hiii…plz send me full code on’ detective.akhilesh@gmail.com

  • surendra

    plz send me source code of second part my email ID surendra88meena@gmail.com

  • Jay Joshi

    Hello,
    Can I get the source code of fragment_main.xml please?
    Thanks

  • Tomás Rodrigues

    can you send me source code of all (including layout.xml)? plz tomasrodrigues@ua.pt

  • Mihir Gadkari

    hi

  • Mihir Gadkari

    I have created Android project with exactly the same code as given in this tutorial. I am using Openfire as a XMPP server. I am able to establish connection with server through my app successfully. But whenever I click the “Send” button, I am not able to receive the message. Getting the following error in Logcat.

    98cedeed-4a3a-4b9f-801a-4e90c0076c80

    Please help me understand what is going wrong in my code.

    • Mihir Gadkari

      Resolved the issue myself .
      In the strings.xml, for the “server” value, initially I was adding the IP address of the server.

      But after changing the “server” value in strings.xml to “Server Name” in “Server Properties” under Server -> Server Manager -> Server Information in Openfire admin console, the issue got resolved. Now able to receive messages from one user to other.

      • Eloy

        Hello Mihir, could you share the strings.xml file?
        My e-mail address is eloybayer@hotmail.com
        thanks in advance

  • Venkatesh Degala

    can you send me source code of all (including layout.xml)? plz venkateshdegala8@gmail.com

  • Venkatesh Degala

    Hi, can you send me source code of all (including layout.xml)? plz venkateshdegala8@gmail.com

  • vishal

    Getting Error java.lang.NoClassDefFoundError: Failed resolution of: Lorg/jxmpp/util/XmppStringUtils;
    Am not able to get it. Imported all lib through Gradle.
    Please Help!

    • Gagana Marrikuppala

      have you solved the problem

    • Gagana Marrikuppala

      even i’m facing same error…..have u solved problem

  • Eloy

    Hello, I got this: Error:(66, 51) error: cannot find symbol variable pager
    Could you help me?

  • Oliver Bob

    I would say it would be great if you can share a link where we can download the full code to this project. I truly appreciate this tutorial.

  • http://twicekenyablog.blogspot.co.ke Peter musumbi

    please include project clone or zip. am using my phone so I can’t follow initial projects steps. send zip or link to it to petermusumbi@gmail.com. thanks in advance.

    • Pushpendra
      • Ramanuj Basu

        Hello Pushpendra

        The project is not working in SDK Version 24.0.2, As the version of SDk in your project is 25, After I decrease the version , the project wont working.

        If you help me out in this.

        Thank you
        Ramanuj Basu

  • Kanwar preet

    In MyXMPP Class…………………..

    Mychat = ChatManager.getInstanceFor(connection).createChat(chatMessage.receiver + “@” + context.getString(R.string.server), mMessageListener);

    Wrong 1st argument type. Found: ‘java.lang.String’, required: ‘org.jxmpp.jid.EntityJid’ less…

    createChat(org.jxmpp.jid.EntityJid,ChatMessageListener)

    in ChatManager cannot be applied to

    (java.lang.String,MMessageListener)

    • james hunt

      did you get the solution ? for R.string.server : cannot resolve symbol ‘server’.

  • Kanwar preet

    This is the Overrided method

    @Override

    public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {

    }

    How can you replace Jid parameters with String.

    @Override

    public void onReceiptReceived(final String fromid, final String toid, final String msgid, final Stanza packet) {

    }

  • Kanwar preet

    Please Mail Me project as Zip !
    Preetkewl@gmail.com

    Thank You

  • samson

    Anyone know how to fix the MyXMPP$MMessageListener.processMessage error? I’m receiving the message however once it hits the line Chats.chatlist.add(chatMessage) i get “Attempt to invoke virtual method ‘boolean java.util.ArrayList.add(java.lang.Object)’ on a null object reference”. I know the message comes through because it displays the message in the android monitor though log.

    All help will be greatly appreciated, thank you!

    • samson

      dw guys it i had my chatlist in my mainactivity that was my problem

  • Nikola Djurovic

    I get the error java.lang.RuntimeException: An error occured while executing doInBackground(), it crashes when doing connection.connect() in the asynctask, anyone have any ideas why?

  • Gagana Marrikuppala

    Getting Error
    java.lang.NoClassDefFoundError: Failed resolution of:
    Lorg/jxmpp/util/XmppStringUtils;
    Am not able to get it. Imported all lib through Gradle.
    Please Help!

  • Nikola Djurovic

    java.lang.NoClassDefFoundError: javax.swing.ImageIcon

    Why am I getting this when it tries connection.connect(); in the doinbackground

  • Ramanuj Basu

    Hello Sir,

    I followed your instruction and I have downloaded all the jar files according to your link you provide and also the org folder, Now when I suppose to Integrate the class “MyXMPP ” the import/package is showing missing. I figure it out that there is no such import “import org.jivesoftware.smack.tcp.XMPPTCPConnection;
    import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;” . And i found that on the jar folder there is no such sub folder called ” tcp ” in the jar files which causes the problem. I got stuck into a problem. Any help will be appreciable.

    • james hunt

      Dear, download the smack libraries for smack_4_1_9.zip from http://download.igniterealtime.org/smack/, extract the zip find the lib folder and there you can find the smack-tcp-4.1.9.jar file. This is the lib file you need to add to your project in the same way you added others. Your issue will be solved for sure. Thanks, have a nice day.

  • kardinal 1

    hello … i fond your tutorial very intersting ..me i want to integrate the voice calling to the chat can you help me or give an idea . thanx

  • kardinal 1

    hello … i found your tutorial very interesting ..me i want to integrate the voice calling to the chat can you help me or give me an idea . thanks

  • Suvendu Pradhan

    how can get the chat history ?

  • Mudra Patel

    I am facing this issue.

    3-06 12:26:54.448 14252-14379/com.intellinect.intel.chatapplicationnew D/SMACK: RECV (0):
    03-06 12:26:54.452 14252-14325/com.intellinect.intel.chatapplicationnew W/System.err: org.jivesoftware.smack.sasl.SASLErrorException: SASLError using DIGEST-MD5: not-authorized
    03-06 12:26:54.457 14252-14325/com.intellinect.intel.chatapplicationnew W/System.err: at org.jivesoftware.smack.SASLAuthentication.authenticationFailed(SASLAuthentication.java:365)
    03-06 12:26:54.457 14252-14325/com.intellinect.intel.chatapplicationnew W/System.err: at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1033)
    03-06 12:26:54.457 14252-14325/com.intellinect.intel.chatapplicationnew W/System.err: at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
    03-06 12:26:54.457 14252-14325/com.intellinect.intel.chatapplicationnew W/System.err: at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
    03-06 12:26:54.457 14252-14325/com.intellinect.intel.chatapplicationnew W/System.err: at java.lang.Thread.run(Thread.java:818)

    Please help

  • Waseem

    lt – Cannot resolve symbol ‘lt’
    gt – Cannot resolve symbol ‘gt’
    ) – Expression expected

    • Ravi Garimella

      just delete the & sybl

  • Jayakrishnan

    Hi guys

    iam not getting any error in program.But while iam running the program it is not executing and showing application as stopped.

    I think problem in ActionBar.TabListener it showing dashline in TabListener. and i have changed to TabLayout.onTabSelectedListener it not working getting same prblm. So from long time iam facing this problem can anyone solve this problem plzzz……

    getting dashline on this codes too.

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mViewPager
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
    actionBar.setSelectedNavigationItem(position);
    }
    });

    MainActivity.java:

    public class MainActivity extends AppCompatActivity implements
    ActionBar.TabListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    doBindService();

    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mSectionsPagerAdapter = new SectionsPagerAdapter(
    getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
    actionBar.setSelectedNavigationItem(position);
    }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

    actionBar.addTab(actionBar.newTab()
    .setText(mSectionsPagerAdapter.getPageTitle(i))
    .setTabListener(this));
    }
    }

  • Pankaj

    Which method or class working for receiving message i am not able to debug that class or method. Please help.
    Thanks

  • uremgba chisom

    please i followed this tutorial to the fragment class, but i cant find this method

    bindService(new Intent(this, Myservice.class), mConnection, Context.BIND_AUTO_CREATE);

    and the

    unBindService(mConnection);

    i cant find the implementations of this 2 methods and thats all thats holding me back now.
    thanks in anticipation.

    myEmail: peterstevofficial@gmail.com
    whatsapp (preferable): +2348067803550

  • Simran Sharma

    it show me error in myxamp and chatadapter file cannot import and support please help me what i do

  • Simran Sharma

    how you paste here org.jxmpp file please help me

  • Simran Sharma

    hi..from where i download this clone please help me this please reply as soon as possible

  • Auxano Services

    Where i can found “activity_main.xml” file source code?

  • Aniketh Jain

    Can I have a java backend service which has the MyXmPP java and then communicate with the service through my android client? and have chat listener in the android client to listen for new messages? Is that possible ? I am very new to this domain.

  • erzi hidayat

    thanks so much for making this tutorial