Download Code

Web Server Based Chat Room Android

In this tutorial you will learn how to create web server based chat room Android.There are two sides of this chat room

  • Chat Room Android End.
  • Website Chat Room End.

So,First you will develop website end.Do the following steps first.

  • Find codecChatRoom(PHP Files) > Chat Directory is for Web End > other files for Android to Server API.
  • Put it in XAMPP > htdocs directory.
  • Create new database and table.
  • Table with two attributes id,message.

I am giving you the source code of web end which look like this.

Chat Room android,asynctask,asynctask in android,how to load data using asynctask, how to load data from database using asynctask,how to load data from localhost in android,JSON,JSONParser,JSONObject,JSONArray,getJSONString, http,httpclient,httppost,httpget,how to parse data using JSON, how to parse data using JSON in android,parse data using JSON android, chat room in android,chat room,group chat in android,group chat android, web server based group chat,web server based group chat in android, database,php,mysql,how to load data from php/mysql,how to load data using JSON, inputstream,bufferedstream,inputstreamreader,android group chat, android group chat tutorial,android group chat source code, httpentity,runonuithread,parallelcomputation,parallelcomputation in android,

Let’s start to create Chat Room Android End.Create new android application project.Go to activity_main.xml and add following UI components.

  • ListView
  • TextView with TableRow
  • EditText
  • Button

Chat Room android,asynctask,asynctask in android,how to load data using asynctask, how to load data from database using asynctask,how to load data from localhost in android,JSON,JSONParser,JSONObject,JSONArray,getJSONString, http,httpclient,httppost,httpget,how to parse data using JSON, how to parse data using JSON in android,parse data using JSON android, chat room in android,chat room,group chat in android,group chat android, web server based group chat,web server based group chat in android, database,php,mysql,how to load data from php/mysql,how to load data using JSON, inputstream,bufferedstream,inputstreamreader,android group chat, android group chat tutorial,android group chat source code, httpentity,runonuithread,parallelcomputation,parallelcomputation in android,

Next MainActivity.java and do the following steps for Chat Room Android Layout.

  • Create variables of ListView,EditText and Button.
  • Create variables for inputstream etc.
  • Refer UI component id’s in class and apply click event on button.
  • Create asynctask class for sending message to database.
  • Method for message display from database.

MainActivity.java

package developer.codecchatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;


public class MainActivity extends Activity implements OnClickListener{
	EditText message;   // edit text variable where user input message
	Button send;		// send message button
	InputStream is=null;   // input stream setting to null
	String result=null;    // result null
	String line=null;      // line string to null at the start
	int code;			
	String msg;
	ListView mess;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        connect();
		initialize();
		new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       connect();   
                    }
                });
            }
        }, 0, 5000);

	}


	public void initialize(){
		message = (EditText) findViewById(R.id.msg);
		send = (Button) findViewById(R.id.msgSend);
		send.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.msgSend:
			msg = message.getText().toString();
			new insertDATA().execute();
			message.setText("");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				connect();
			
			
			
			
			
			break;
		}
	}
	
	
	
	private void connect() {
	      String data;
	      List r = new ArrayList();
	      ArrayAdapteradapter=new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,r);
	      mess=(ListView)findViewById(R.id.allmessages);
	      mess.setStackFromBottom(true);
	        try {
	            DefaultHttpClient client = new DefaultHttpClient();
	            HttpGet request = new HttpGet("http://your_localhost_ip/codecChatRoom/chat/allmessages.php");
	            HttpResponse response = client.execute(request);
	            HttpEntity entity=response.getEntity();
	            data=EntityUtils.toString(entity);
	            Log.e("STRING", data);
	            try {
	             
	       JSONArray json=new JSONArray(data);
	       for(int i=0;i<json.length(); i++)
	       {
	        JSONObject obj=json.getJSONObject(i);
	        String update=obj.getString("message");
	      
	        Log.e("STRING", update);
	        r.add(update);
	       
	        mess.setAdapter(adapter);
	        
	       }
	       
	      } catch (JSONException e) {
	       // TODO Auto-generated catch block
	       e.printStackTrace();
	      }
	          
	        } catch (ClientProtocolException e) {
	            Log.d("HTTPCLIENT", e.getLocalizedMessage());
	        } catch (IOException e) {
	            Log.d("HTTPCLIENT", e.getLocalizedMessage());
	        }
	      
	      
	    }
	
	
	///
	
	
	class insertDATA extends AsyncTask<String, String, String> {


		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			ArrayList values = new ArrayList();

			values.add(new BasicNameValuePair("message", msg));


			try {
				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://your_localhost_ip/codecChatRoom/chat/chatuser.php");
				httppost.setEntity(new UrlEncodedFormEntity(values));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				Log.i("TAG", "Connection Successful");
			} catch (Exception e) {
				Log.i("TAG", e.toString());
				//Invalid Address
			}

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
				Log.i("TAG", "Result Retrieved");
			} catch (Exception e) {
				Log.i("TAG", e.toString());
			}

			try {
				JSONObject json = new JSONObject(result);
				code = (json.getInt("code"));
				if (code == 1) {
					Log.i("msg", "Data Successfully Inserted");
					
					//Data Successfully Inserted
				} else {
					//Data Not Inserted
				}
			} catch (Exception e) {
				Log.i("TAG", e.toString());
			}
			return null;
		}
		}
}

Now let’s talk about API for Android application.Create PHP API to handle messages.Application will show only 250 recent messages.
chatuser.php

Chat Room android,asynctask,asynctask in android,how to load data using asynctask, how to load data from database using asynctask,how to load data from localhost in android,JSON,JSONParser,JSONObject,JSONArray,getJSONString, http,httpclient,httppost,httpget,how to parse data using JSON, how to parse data using JSON in android,parse data using JSON android, chat room in android,chat room,group chat in android,group chat android, web server based group chat,web server based group chat in android, database,php,mysql,how to load data from php/mysql,how to load data using JSON, inputstream,bufferedstream,inputstreamreader,android group chat, android group chat tutorial,android group chat source code, httpentity,runonuithread,parallelcomputation,parallelcomputation in android,
allmessages.php

Chat Room android,asynctask,asynctask in android,how to load data using asynctask, how to load data from database using asynctask,how to load data from localhost in android,JSON,JSONParser,JSONObject,JSONArray,getJSONString, http,httpclient,httppost,httpget,how to parse data using JSON, how to parse data using JSON in android,parse data using JSON android, chat room in android,chat room,group chat in android,group chat android, web server based group chat,web server based group chat in android, database,php,mysql,how to load data from php/mysql,how to load data using JSON, inputstream,bufferedstream,inputstreamreader,android group chat, android group chat tutorial,android group chat source code, httpentity,runonuithread,parallelcomputation,parallelcomputation in android,
At last go to Android Manifest.xml file and add INTERNET AND ACCESS_NETWORK_STATE permissions.

Chat Room android,asynctask,asynctask in android,how to load data using asynctask, how to load data from database using asynctask,how to load data from localhost in android,JSON,JSONParser,JSONObject,JSONArray,getJSONString, http,httpclient,httppost,httpget,how to parse data using JSON, how to parse data using JSON in android,parse data using JSON android, chat room in android,chat room,group chat in android,group chat android, web server based group chat,web server based group chat in android, database,php,mysql,how to load data from php/mysql,how to load data using JSON, inputstream,bufferedstream,inputstreamreader,android group chat, android group chat tutorial,android group chat source code, httpentity,runonuithread,parallelcomputation,parallelcomputation in android,

Run your android application project.

Chat Room android,asynctask,asynctask in android,how to load data using asynctask, how to load data from database using asynctask,how to load data from localhost in android,JSON,JSONParser,JSONObject,JSONArray,getJSONString, http,httpclient,httppost,httpget,how to parse data using JSON, how to parse data using JSON in android,parse data using JSON android, chat room in android,chat room,group chat in android,group chat android, web server based group chat,web server based group chat in android, database,php,mysql,how to load data from php/mysql,how to load data using JSON, inputstream,bufferedstream,inputstreamreader,android group chat, android group chat tutorial,android group chat source code, httpentity,runonuithread,parallelcomputation,parallelcomputation in android,

That’s it for this tutorial.

Thanks.