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

By | August 26, 2015

Today we will develop a chat application from scratch for android. We will use XMPP (ejabberd) hosted on aws EC2.

I will be developing this app using Eclipse IDE with adt plugin.
Create a new android application project in eclipse.
Choose tabbed activity while creating the project.(see screenshot below)
Select “Action bar tabs (with viewpager)” for Navigation style as show below.




Now as the project is created, just try to run this project and you will see an empty app with three tabs named Secion1, Section2, Section3 as shown below:
Now change name of the three tabs to Favourites, Chats, Contacts respectively.
To do this, change the content of the string.xml file located at res/values/string.xml in your project directory to the code below.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MChat</string>
    <string name="title_section1">Favourites</string>
    <string name="title_section2">Chats</string>
    <string name="title_section3">Contacts</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>
Now run the application.
Now as we have added tabs layout, we will work on the tab “Chats”.
 
Download the 9 patch images below and and move them to drawable-hdpi in res directory of your project.
 OR
You can find the image resources required for the layout files here
 
Create an xml file res/drawable/send_button.xml. If drawable folder does not exist in your res directory then create it.
The contents for the send_button.xml will be:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"
android:state_pressed="false" 
android:drawable="@drawable/send_selected" />
    <item android:state_focused="true" 
      android:state_pressed="true"
      android:drawable="@drawable/send_selected" />
    <item android:state_focused="false" 
      android:state_pressed="true"
  android:drawable="@drawable/send_selected" />  
    <item android:drawable="@drawable/send" />
</selector>
Now Create a new layout file chat_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#e1e1e1"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/msgListView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/form"
        android:divider="@null"
        android:dividerHeight="0dp"
        android:paddingBottom="10dp"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="#91f1f1f1"
        android:orientation="horizontal"
        android:paddingBottom="2dp" >

       
        <EditText
            android:id="@+id/messageEditText"
            android:layout_width="252dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignTop="@+id/button1"
            android:layout_toLeftOf="@+id/sendMessageButton"
            android:layout_weight="0.72"
            android:ems="10"
            android:maxHeight="80dp" />

        <ImageButton
            android:id="@+id/sendMessageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:background="@drawable/send_button"
            android:text="d" />
    </LinearLayout>


</RelativeLayout>
This will be layout file which will provide interface for sending and receiving chat messages.
The layout contains:
i) A Listview which will have entries for sent and received messages.
ii) An EditText view for writing new message.
ii) A Button view to send message.
See the graphical Layout below:

We will be using a custom adapter for our Listview.  So in order to follow that we will need another layout file for each entry of the listview.
Create another layout file chatbubble.xml as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bubble_layout_parent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/bubble_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bubble1">

        <TextView
            android:id="@+id/message_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxEms="12" 
            android:layout_gravity="center"
            android:text="Hi! new message"
            android:textColor="@android:color/primary_text_light" />
    </LinearLayout>

</LinearLayout>
In this layout file we have another LinearLayout inside the parent LinearLayout. This is done because we need to change the position of the message according to the sender of the message. For example if a message is sent by you, then it should be aligned right of the screen and if the message is received from another user then it should be aligned left of the screen.
Below is the graphical layout of th chatbubble.xml:
Now create a new package named com.marothiatechs.fragments inside src folder of your project.
create a new Java file in this new package and name it Chats.java
The contents of 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.R;

public class Chats extends Fragment implements OnClickListener {

	private EditText msg_edittext;
	private String user1 = "khushi", user2 = "khushi1";
	private Random random;
	public static ArrayList&lt;ChatMessage&gt; 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&lt;ChatMessage&gt;();
		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();
		}
	}

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

		}
	}

}
Create a new file named ChatMessage.java in the package com.marothiatechs.mchat:
package com.marothiatechs.mchat;

import java.util.Random;

public class ChatMessage {

	public String body, sender, receiver, senderName;
	public String Date, Time;
	public String msgid;
	public boolean isMine;// Did I send the message.

	public ChatMessage(String Sender, String Receiver, String messageString,
			String ID, boolean isMINE) {
		body = messageString;
		isMine = isMINE;
		sender = Sender;
		msgid = ID;
		receiver = Receiver;
		senderName = sender;
	}

	public void setMsgID() {

		msgid += "-" + String.format("%02d", new Random().nextInt(100));
		;
	}
}
Create a new file named ChatAdapter.java in the package com.marothiatechs.mchat:
package com.marothiatechs.mchat;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ChatAdapter extends BaseAdapter {

	private static LayoutInflater inflater = null;
	ArrayList&lt;ChatMessage&gt; chatMessageList;

	public ChatAdapter(Activity activity, ArrayList&lt;ChatMessage&gt; list) {
		chatMessageList = list;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}

	@Override
	public int getCount() {
		return chatMessageList.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ChatMessage message = (ChatMessage) chatMessageList.get(position);
		View vi = convertView;
		if (convertView == null)
			vi = inflater.inflate(R.layout.chatbubble, null);

		TextView msg = (TextView) vi.findViewById(R.id.message_text);
		msg.setText(message.body);
		LinearLayout layout = (LinearLayout) vi
				.findViewById(R.id.bubble_layout);
		LinearLayout parent_layout = (LinearLayout) vi
				.findViewById(R.id.bubble_layout_parent);

		// if message is mine then align to right
		if (message.isMine) {
			layout.setBackgroundResource(R.drawable.bubble2);
			parent_layout.setGravity(Gravity.RIGHT);
		}
		// If not mine then align to left
		else {
			layout.setBackgroundResource(R.drawable.bubble1);
			parent_layout.setGravity(Gravity.LEFT);
		}
		msg.setTextColor(Color.BLACK);
		return vi;
	}

	public void add(ChatMessage object) {
		chatMessageList.add(object);
	}
}
Create a new file named CommonMethods.java in the package com.marothiatechs.mchat:




package com.marothiatechs.mchat;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CommonMethods {
	private static DateFormat dateFormat = new SimpleDateFormat("d MMM yyyy");
	private static DateFormat timeFormat = new SimpleDateFormat("K:mma");

	public static String getCurrentTime() {

		Date today = Calendar.getInstance().getTime();
		return timeFormat.format(today);
	}

	public static String getCurrentDate() {

		Date today = Calendar.getInstance().getTime();
		return dateFormat.format(today);
	}

}

Modify the contents of MainActivity.java:
 You need to replace the getItem() method in SectionsPagerAdapter class inside MainActivity.java as shown below:
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;
}
}

 

 
Now Run the application, go to Chats tab and  try to send any message. You will notice that a new entry with a bubble is added to the listview.
The screenshot of the app so far:
We will implement the Smack 4.1 implementation using Android service in  Part-2.

127,253 total views, 171 views today

(Visited 129,516 times, 136 visits today)
  • Pingback: Building your own android chat messenger app similar to Whatsapp using XMPP (Smack 4.1 API) from scratch: Part-2 | Tutorials Face()

  • http://www.yantrajaal.com Prithwis Mukerjee

    Dear Friend, Thank you very much for this detailed post, that I have been looking for quite some time. I have followed all the steps so far but have had three problems
    (1) The import android.support.v7 cannot be resolved : this was addressed through this post : http://stackoverflow.com/questions/24998368/the-import-android-support-v7-cannot-be-resolved
    The bigger problem is this
    (2) Once I do the change suggested in MainActivity, namely\
    ——————————————————————————
    @Override
    public Fragment getItem(int position) {
    if (position == 1) {
    return new Chats();
    } else
    return PlaceholderFragment.newInstance(position + 1);
    }
    ——————————————————————————-
    i get an error on the return new Chats() statement as follows :
    “Type mismatch: cannot convert from Chats to Fragment”

    (3) I tried replacing return new Chats() with return new Fragment()
    this removed the error, program compiled and executed BUT the chat_layout and the chatbubble screens did not come up. there was no text input area nor the send button.
    So effectively the program was not working.

    Would be grateful if you can help out with this problem.

    • Laxman Marothiya

      Hi,

      You cannot use “return new Fragment()” in place of “return new Chats()”. This might be the reason for your not getting the chat_layout and chatbubble screens.

      The chat_layout.xml is used as a layout file inside Chats.java fragment class but you are simply returning a new Fragment() instead of Chats().

      The error: “Type mismatch: cannot convert from Chats to Fragment” tells that your Chats.java class might not be extending a proper Fragment.
      Make sure that wherever the Fragment name is used in your project, you import the below Fragment:

      import android.support.v4.app.Fragment;

      I hope this solves your problem. 🙂

      • http://www.yantrajaal.com Prithwis Mukerjee

        thank you for your quick response ….
        Chats.java has (among others) these imports
        ———————————————————————–
        import android.support.v4.app.Fragment;
        import android.support.v7.app.ActionBarActivity;

        ———————————————————————–
        which is what was there in the sample program that you have kindly supplied

        • Laxman Marothiya

          Please make sure that the same imports are there in your MainActivity.java

          • http://www.yantrajaal.com Prithwis Mukerjee

            //import android.app.Fragment;
            import android.support.v4.app.Fragment;
            commented out the the original import, and put in the new import
            now error on new Chats() gone by new error on public Fragment ..
            —————————————
            @Override
            public Fragment getItem(int position) {
            if (position == 1) {
            return new Chats();
            } else
            return PlaceholderFragment.newInstance(position + 1);
            }
            ——————————————
            Multiple markers at this line
            – implements android.support.v13.app.FragmentPagerAdapter.getItem
            – The return type is incompatible with
            FragmentPagerAdapter.getItem(int)
            ———————————————
            Eclipse suggest that I change it to

            @Override
            public android.app.Fragment getItem(int position) {
            if (position == 1) {

            but by doing that we get back the old error plus other errors.
            sorry, for being such a pain … but appreciate your help

          • Laxman Marothiya

            Import these and let me know if errors persist:

            import android.support.v4.app.Fragment;
            import android.support.v4.app.FragmentManager;
            import android.support.v4.app.FragmentPagerAdapter;
            import android.support.v4.app.FragmentTransaction;

            I think you have different android support library version, just try to use same path for every Fragment related import, for example:

            import SAME_PATH.Fragment;
            import SAME_PATH.FragmentManager;
            import SAME_PATH.FragmentPagerAdapter;
            import SAME_PATH.FragmentTransaction;

          • http://www.yantrajaal.com Prithwis Mukerjee

            with the following imports i get 1 error
            —————————————————-
            import android.app.Fragment;
            import android.app.FragmentManager;
            import android.app.FragmentTransaction;
            import android.support.v13.app.FragmentPagerAdapter;
            —————————————————–

            but with these support.v4 imports i get 8 errors (including the original error)
            ——————————————————
            import android.support.v4.app.Fragment;
            import android.support.v4.app.FragmentManager;
            import android.support.v4.app.FragmentTransaction;
            import android.support.v4.app.FragmentPagerAdapter;
            ——————————————————–
            so clearly we are off the track here …

            the android libraries that are in my build path are

            /home/hduser/android-sdks/platforms/android-23/android.jar
            /home/hduser/workspace/PMChat2/libs/android-support-v13.jar
            /home/hduser/android-sdks/extras/android/support/v7/appcompat/libs/android-support-v7-appcompat.jar
            /home/hduser/android-sdks/extras/android/support/v4/android-support-v4.jar

            thanks for your patience and help. wondering if we should take this offline? you can, if you wish to, contact me at p r i t h w i s at y a n t r a j a a l dot c o m

          • Dominika K

            Did you solve this problem? I’ve got the same error 🙁

          • http://www.yantrajaal.com Prithwis Mukerjee

            No, this approach led me nowhere. Instead tried something else and it worked. Have built an XMPP based Android application and the details are given here http://www.iot-hub.org/2015/10/lightwatch-iot-prototype-using-xmpp-and.html

          • spu7nik

            Solved the Problem, in ‘Chats.java’ delete the line ‘

            ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(“Chats”);’
            For me its working fine now

          • http://www.yantrajaal.com Prithwis Mukerjee

            perhaps the problem lies somewhere here :

            [2015-10-11 07:48:38 – PMChat2] WARNING: Found both android-support-v4 and android-support-v13 in the dependency list.

            [2015-10-11 07:48:38 – PMChat2] Because v13 includes v4, using only v13.

            will keep trying 🙂

          • http://www.yantrajaal.com Prithwis Mukerjee

            End of the road for a bridge to far !
            Could never eliminate that one last error.
            Will now have to look for another solution. Thanks anyway

    • Fison

      make sure that Chats and MainActivity classes are stored in the some folder(packages), i mean don’t put them in different location of your app. if you put them in defferent package then your will need to import the package.

      even me i was face the same problem but new is ok
      see the image:….

      • Fison

        don’t replace Chats() with Fragments(). but put them in the same directory it will works.

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

      Hi! This is because chat_layout is located below the screen, and you can’t see it.
      I changed expression if (position == 1) to if (position == 0) and see that numeric keyboard appeared. I entered some words and they appeared in the bottom of the screen.

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

      chat_layot-linearlayout
      android:paddingBottom=”50dp”
      and chat will be visible.

      • Abhishek Singh

        thank you. Truly helpful….

  • great summit an

    What string is R.string.server?

    • Pramod Raghav

      its the name of your XMPP server.

      • Dominika K

        I have a problem with it in MyXMPP.java file, in SendMessage method, it says: Cannot resolve symobl ‘server’. Does anybody know how to fix it?

  • Amitoj

    Awesome tutorial. However, at the end of the tutorial, the “Chat” tab looks completely blank.
    I just downloaded the latest Android Studio along with the SDK. The default “tabs” project has changed in new android studio and hence I had to make a few changes to your code.
    1. ActionBarActivity is deprecated. So had to use AppCompatActivity in Chats.java.
    2. Page titles are now hardcoded in “MainActivity.java” instead of “strings.xml”.

    Also, preview images in android studio look exactly the same as in your tutorial. So I guess something breaks down at runtime.

    I can’t figure out how these changes could have broken the code. Any suggestions?

    • Fison

      me 2 i has face the problem, but now is ok

      1) i made a modification in Activity_Main.xml
      —————————————————–

      xmlns:android=”http://schemas.android.com/apk/res/android” />

      <!– –>

      <!– >

      <!—->

      i add …… and comment some code inside

      2) i made a modification in MainActivity
      only comment This

      /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
      fab.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View view) {

      Snackbar.make(view, “Replace with your own action”, Snackbar.LENGTH_LONG)

      .setAction(“Action”, null).show();

      }

      });

      */

      • Amitoj

        Yea, that was my exact problem. I solved it using Linearlayout, instead of RelativeLayout. Is there any dis-advantage of using Linearlayout over RelativeLayout?

      • oops

        Actually I am not getting you..can u plz explain this further???

  • Fison

    May Be some change must be mode try this

    if you get things like this “<” or “>” replace it with “sign”

    for me to run it, i change this:
    1)ActionBarActivity is deprecated. So i use AppCompatActivity in Chats.java.
    2) public class MainActivity extends AppCompatActivity instead of ActionBarActivity
    3) i made a modification in Activity_Main.xml

    —————————————————–

    xmlns:android=”http://schemas.android.com/apk…” />

    >

    i add …… and comment some code inside

    4) i made a modification in MainActivity

    only comment This

    /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

    Snackbar.make(view, “Replace with your own action”, Snackbar.LENGTH_LONG)

    .setAction(“Action”, null).show();

    }

    });

    */

  • DarkVision

    i manage to make it work but why my message doesn’t fit the bubble the more i type and the more the bubble look ugly

  • Pingback: What are all need to make app? – My library()

  • Venkata Naga

    Can anybody please share the source code zip file.:)

  • Deepank Dwivedi

    Can someone mail me the source code or share on drive my gmail id is deepankdwivedi@gmail.com

  • Maneesh Kumar Gaud

    can you help in chatadapter class…

    • saif

      What problem do you face?

      • Maneesh Kumar Gaud

        Even when i select the chat tab, i get empty layout. I am sure return
        new Chats(), is being executed, as the welcome text gets cleaned up.
        need help..

  • saif

    I am new to android, excellent tutorial. As others posted there are few things I did change for example like the AppCompatActivity. I also changed &lt to “”. However, I am not see the chat bubble thing shown in the final screenshot of part-1, no errors either.. need help..

  • Mayank Patel

    give me full code of this app

  • aamobile games

    thanks for this tutorial.
    But even if I did every thing same, when I click Chat tab a blank page comes up. But if I change RelativeLayout to LinearLayout in chat_layout.xml I can see the content. But Send message buttone is not the correct place. Can someone help me?

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

      chat_layot-linearlayout
      android:paddingBottom=”50dp”
      and chat will be visible.

  • eki ashadi

    can you send to me the source code please??? ekiashadi88@gmail.com
    thanks you

  • crazy student

    I am making this chat app in Android studio…..there I couldn’t find “src” folder but created by by choosing file>new>package….after that it asked me to “choose destination directory” there I have chosen “…appsrcmainjavamarothiatechs” after that asked me to “enter new package name:” there I have entered “fragments”
    .
    .

    I hope above step is right.
    .
    .
    But the problem what I am facing is in Chats.java
    chatlist = new ArrayList<ChatMessage>();
    in the above line following errors are coming:
    chatlist – Cannot resolve symbol ‘chatlist’
    & – ‘(‘ or ‘[‘ expected
    lt – Cannot resolve symbol ‘lt’
    gt – Cannot resolve symbol ‘gt’
    ) – Expression expected
    in the line
    chatAdapter = new ChatAdapter(getActivity(), chatlist);
    error is for chatlist as
    Cannot resolve symbol ‘chatlist’
    .
    .
    In ChatAdapter.java
    similar errors are present
    as well as additional error for
    chatMessageList = list;
    where for “chatMessageList” and “list” Cannot resolve symbol error is coming.
    .
    .

    • Kathureliz

      Hi Crazy Student I’m having similar issues with my Chats.java and ChatAdapter.java how did you resolve your errors ?

    • pammy

      in place of lt and gt just put less than sign

  • Raja Mohamed

    error

  • Raja Mohamed

    Error:(20, 14) error: expected

  • Raja Mohamed

    anyone solve Error:(20, 14) error: expected issue

  • jaffa reddy

    Getting error in Chats.java and Chatadapter.java particularly at & in
    private static LayoutInflater inflater = null;
    ArrayList<ChatMessage> chatMessageList;

  • Guruprasad N

    It was a great tutorial, but i have some error over in the ChatAdapter.java section

    public class ChatAdapter extends BaseAdapter {

    private static LayoutInflater inflater = null;
    ArrayList<ChatMessage> chatMessageList;

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

    }
    In this code after the ampesant symbol it keeps ahowing an error “lt” and “gt”
    Which in turn makes the chats.java file not work because of the import! Can you please help me ?

    • ChrisSK

      I’m having the same problems.

      It seems there was a blog post error in HTML encoding:

      < should be

      … so it is a normal variable definition:

      ArrayList<ChatMessage> chatMessageList;
      ArrayList chatMessageList;

      ——-
      And there are some imports missing like:

      import com.marothiatechs.fragments.Chats; (in MainActivity)

      But I am still struggling with the following expression in multiple variants:

      R.id.msgListView
      R.id.messageEditText
      R.id.msgListView

      Any ideas on how to solve this problem?

      • Guruprasad N

        ActionBarActivity is depreciated try using AppCompatActivity. Am currently debugging the same problem.

  • Guruprasad N

    I am having an error in the MainActivity.java file

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

    that R.id.pager “pager” is an error i cant find anything called pager in the xml aswell can someone help me ?

  • saran charan

    ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle( “Chats”);

    It says ActionBarActivity is depricated and is unable to cast the object.
    Which results in complete crash of the app. ??????
    if i change the “public class Fragment to Appcompatactivity” oncreteview and onclick methods are not calling ??? wat to do ?

  • jude

    Very very awesome tutorial. Please can you give a step by step instruction on how you setup XMPP (ejabberd) hosted on aws EC2 or alternatives.

  • Joe Henry Olsen

    Dear Author, thanks for a good tutorial which actually works just fine on my side. however, i want to expand the ideal and use it for creating a chatbot. i have a string which contains guessed words from user and their replies respectively. the replies works fine on desktop version. problem is, i don’t know how to connect the reply considering user inputs using this style. how can i achieve separating user inputs and the replies on right and left side respectively? i can send the codes if necessary.
    forgive me if my question is out of topic but i looked everywhere for this style of messages and this is the only one that worked. thanks.

  • Anmol Narang

    public static ArrayList<ChatMessage> chatlist;

    I’m facing error in this line. It says identifier expectedor unexpected tokken in ‘&lt’ someone plzz help

  • aspire vision

    is there any use of xmpp client in this app

  • atefeh

    Hi, Thank you for your post,
    when add this code

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

    I get this error, This monitor is disabeld!
    Can you help me? Thank very much.

  • Cyfer

    In Chats.java the following:
    * public static ArrayList<ChatMessage> chatlist;
    *chatlist = new ArrayList<ChatMessage>();
    * chatAdapter = new ChatAdapter(getActivity(), chatlist);
    lines have errors, i copied and pasted the code exactly making sure nothing got left out, same issue also occures in the ChatAdapter.java class where the following:
    * ArrayList<ChatMessage> chatMessageList;
    * public ChatAdapter(Activity activity, ArrayList<ChatMessage> list) {
    chatMessageList = list;
    *return chatMessageList.size();
    *ChatMessage message = (ChatMessage) chatMessageList.get(position);
    *chatMessageList.add(object);
    also have errors, can anyone please help.
    i always get cannot resolve symbol error for lt from ArrayList&”lt”, chatlist, and gt

    • Sudheendra Kandi

      IN ChatsAdapter.java

      in place of ampersandlt put less than symbol

      error gets resolved

  • Amadon

    Hi it’s nice tutorial, i am using android studio and i tried it with studio it didn’t work out for me. i followed your tutorial step by step, i got confused at the last class (SectionsPagerAdapter) which you said modify MainActivity. please could you help me out on this? or could you please send me the source code to email id? amadonlinkserv@gmail.com. Thanks in advance.

    • Srivathsan Rajagopal

      Same problem for me too

  • Joel Fioti

    Please guys, i need an help, i get empty layout how can i fixed this please…

  • Neeraj Chandra

    public static ArrayList<ChatMessage> chatlist;
    in Chats.java
    is giving error cannotresolve lt,gt,chatlist
    please help..

    • Gagana Marrikuppala

      in place of < and > replace with

  • Gagana Marrikuppala

    01-08 23:22:07.170 5004-5004/com.marothiatechs.mchat E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.marothiatechs.mchat, PID: 5004
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/jxmpp/util/XmppStringUtils;
    at org.jivesoftware.smack.provider.ProviderManager.getKey(ProviderManager.java:314)
    at org.jivesoftware.smack.provider.ProviderManager.removeIQProvider(ProviderManager.java:217)
    at org.jivesoftware.smack.provider.ProviderManager.addIQProvider(ProviderManager.java:199)
    at org.jivesoftware.smack.provider.ProviderManager.addLoader(ProviderManager.java:128)
    at org.jivesoftware.smack.initializer.UrlInitializer.initialize(UrlInitializer.java:54)
    at org.jivesoftware.smack.SmackInitialization.loadSmackClass(SmackInitialization.java:232)
    at org.jivesoftware.smack.SmackInitialization.parseClassesToLoad(SmackInitialization.java:193)
    at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:163)
    at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
    at org.jivesoftware.smack.SmackInitialization.(SmackInitialization.java:116)
    at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
    at org.jivesoftware.smack.ConnectionConfiguration.(ConnectionConfiguration.java:38)
    at com.marothiatechs.mchat.MyXMPP.initialiseConnection(MyXMPP.java:95)
    at com.marothiatechs.mchat.MyXMPP.init(MyXMPP.java:88)
    at com.marothiatechs.mchat.MyXMPP.(MyXMPP.java:54)
    at com.marothiatechs.mchat.MyXMPP.getInstance(MyXMPP.java:62)
    at com.marothiatechs.mchat.MyService.onCreate(MyService.java:32)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:2877)
    at android.app.ActivityThread.-wrap4(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1427)
    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.ClassNotFoundException: Didn’t find class “org.jxmpp.util.XmppStringUtils” on path: DexPathList[[dex file “/data/data/com.marothiatechs.mchat/files/instant-run/dex/slice-support-annotations-23.4.0_10e0a06c36c1567287fdf3ee91fca4e3985be84d-classes.dex”, dex file “/data/data/com.marothiatechs.mchat/files/instant-run/dex/slice-

  • Gagana Marrikuppala
  • Gagana Marrikuppala

    please help me

  • s l

    Hi. I followed this tutorial. lets say i want to send two sentences. i typed the first sentence and it is added to the listview. but when i type the 2nd sentence and hit send, the first sentence gets added to the list view. anyone else having this problem?

  • Harshal Jaware

    Dear friend i am implement app same as to your post.but it gives the unfortunately error.please guide me.

  • Suvendu Pradhan

    I have implemented this code in my app but chat history not displayed in this app.

  • ronak

    03-21 09:01:30.874 21625-21625/com.marothiatechs.mchat E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.marothiatechs.mchat, PID: 21625
    java.lang.ClassCastException: com.marothiatechs.mchat.MainActivity cannot be cast to android.support.v7.app.ActionBarActivity
    at com.marothiatechs.mchat.Chats.onCreateView(Chats.java:40)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2189)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
    at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
    at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1979)
    at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
    at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
    at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1375)
    at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18809)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2112)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1464)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at andro

  • Khalifa Kane

    tanks you!

  • Oleh Jazz

    Good day, sir. I think, i did all step by step from your tutorial. Realy thank you for it.
    But i have a problem with application. Idk why, but i cant open this application on device emulator. Without any errors. Only “MChat has stopped”. Can you help me, pls? my e-mail: olegtruefalse@gmai.com / or here.

  • Shachak Gil

    Hi, thanks for this post, it’s really helpful.
    I ran into a problem that I don’t know how to fix and maybe someone here could help. Everything runs perfectly, I followed every step of this post and there are no errors in my code. The only problem is that when I try to send a text, nothing happens when I press the send button.
    Does anyone know why this might happen, and perhaps it happened to anyone else here?
    I know this is a very general question, but thanks for the helpers.

  • Simran Sharma

    it show me error in chatsadapter and chats .java fie in chatlist and chatmessagelist how i solve what i do please help me reply soon as possible

  • Gustavo M. Severo

    Very nice! But I didn’t understand where you specify when you send message from tab “Chat” the message goes to tab “Chat”, do you understand what I’m saying?
    Thank you for your attention

  • Ashwin Parmar

    When tap on Chats Tab it will be blank. nothing to show.

  • Akash Kumar

    Thank you tutorials Face I got whatsApp row ui and special thanks for icons.