Hello friends, in this post I will show you How to Create Chat App for Android using PHP, MySQL and GCM. I have already posted about GCM and Push Notifications in my earlier post as these are very important for creating our chat app. So in this post we will create a simple chat room where many users can interact with each other.
This post was very lengthy so I divided it into two parts.Â
Part 1: This part will cover about creating server side codes and APIs.
Part 2: In this part we will actually build our chat application.
Table of Contents
Create Chat App for Android Live Demo
You can also check this video demonstrating the final app that we will make in this tutorial.
You can also get a live demo of the app that we will be building from below. Just download the apk from the link given and install it to your device. But you need two device to check it.
If you tested the apk and want to know how to code it then lets move ahead.
Prerequisite to Create Chat App for Android
- You should follow the previous Android Push Notification Tutorial using GCM.
- You should also follow the REST API tutorial using SLIM Framework.
- Other than the above mentioned tutorial we will be using PHP and MySQL you need a local server like wamp or xampp for it.
It is highly recommended that you go through the above mentioned tutorial before moving ahead on this Create Chat App for Android Tutorial. So lets begin.
Create Chat App for Android Tutorial
In this post we will create server side APIs and in the next post we will built the android application. I am using WAMP server. You can also use other server’s basically what is needed is PHP and MySQL.  So lets start with creating database.
Creating Database
- This is our database model.
- So as you can see we have two tables one is users and other is messages. To create the above tables just copy the following SQL to your phpmyadmin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
-- Created by Simplified Coding https://www.simplifiedcoding.net -- Last modification date: 2016-05-30 15:41:34.537 -- tables -- Table: messages CREATE TABLE messages ( id int NOT NULL AUTO_INCREMENT, message varchar(100) NOT NULL, users_id int NOT NULL, sentat timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT messages_pk PRIMARY KEY (id) ); -- Table: users CREATE TABLE users ( id int NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, email varchar(50) NOT NULL, gcmtoken text NOT NULL, CONSTRAINT users_pk PRIMARY KEY (id) ); -- foreign keys -- Reference: messages_users (table: messages) ALTER TABLE messages ADD CONSTRAINT messages_users FOREIGN KEY messages_users (users_id) REFERENCES users (id); -- End of file. |
- Now we have our database. Time to code our API.
Creating RESTful API
- I am using PHP Storm as I personally feel it is the best IDE. So whatever IDE you are using open it and create a new PHP Project in the WAMP’s root directory (c:/wamp/www). I have created SimplifiedCodingChat.
- Now you have to create the following folder structure as shown in the below screenshot.
- First download SLIM Framework 2.x and paste it inside your libs folder.
- Now inside include folder create 3 php files Config.php, DbConnect.php and DbOperation.php.
- First come inside Config.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); define('DB_NAME', 'db_simplifiedcodingchat'); define('USER_CREATED_SUCCESSFULLY', 0); define('USER_CREATE_FAILED', 1); define('USER_ALREADY_EXISTED', 2); define('GOOGLE_API_KEY','YOUR GOOGLE API KEY'); |
- You may need to change the value of the first 4 constants according to your MySQL database. And you also need to put your Google API Key. If you don’t know what is the google api key please go through the Android Push Notification Tutorial using GCM first.
- Now inside DbConnect.php write the following code. It is used to connect with the MySQL Database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php class DbConnect { private $conn; function __construct() { } /** * Establishing database connection * @return database connection handler */ function connect() { require_once 'Config.php'; // Connecting to mysql database $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); // Check for database connection error if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // returing connection resource return $this->conn; } } |
- In DbOperation.php we will define functions for all the database related operations. Write the following code in DbOperation.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
<?php class DbOperation { private $conn; //Constructor function __construct() { require_once dirname(__FILE__) . '/Config.php'; require_once dirname(__FILE__) . '/DbConnect.php'; // opening db connection $db = new DbConnect(); $this->conn = $db->connect(); } //Function to create a new user public function createUser($name, $email) { if (!$this->isUserExists($email)) { $stmt = $this->conn->prepare("INSERT INTO users(name, email) values(?, ?)"); $stmt->bind_param("ss", $name, $email); $result = $stmt->execute(); $stmt->close(); if ($result) { return USER_CREATED_SUCCESSFULLY; } else { return USER_CREATE_FAILED; } } else { return USER_ALREADY_EXISTED; } } //Function to get the user with email public function getUser($email) { $stmt = $this->conn->prepare("SELECT * FROM users WHERE email=?"); $stmt->bind_param("s", $email); $stmt->execute(); $user = $stmt->get_result()->fetch_assoc(); return $user; } //Function to check whether user exist or not private function isUserExists($email) { $stmt = $this->conn->prepare("SELECT id FROM users WHERE email=?"); $stmt->bind_param("s", $email); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows > 0; } //Function to store gcm registration token in database public function storeGCMToken($id, $token) { $stmt = $this->conn->prepare("UPDATE users SET gcmtoken =? WHERE id=?"); $stmt->bind_param("si", $token, $id); if ($stmt->execute()) return true; return false; } //Function to get the registration token from the database //The id is of the person who is sending the message //So we are excluding his registration token as sender doesnt require notification public function getRegistrationTokens($id){ $stmt = $this->conn->prepare("SELECT gcmtoken FROM users WHERE NOT id = ?;"); $stmt->bind_param("i",$id); $stmt->execute(); $result = $stmt->get_result(); $tokens = array(); while($row = $result->fetch_assoc()){ array_push($tokens,$row['gcmtoken']); } return $tokens; } //Function to add message to the database public function addMessage($id,$message){ $stmt = $this->conn->prepare("INSERT INTO messages (message,users_id) VALUES (?,?)"); $stmt->bind_param("si",$message,$id); if($stmt->execute()) return true; return false; } //Function to get messages from the database public function getMessages(){ $stmt = $this->conn->prepare("SELECT a.id, a.message, a.sentat, a.users_id, b.name FROM messages a, users b WHERE a.users_id = b.id ORDER BY a.id ASC;"); $stmt->execute(); $result = $stmt->get_result(); return $result; } } |
- Inside libs folder create a new folder named gcm and inside it create a new file named gcm.php and write the following code. This file will handle our push notifications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?php class GCM { function __construct() { } //This function will send message to the given registration ids //We are also passing a message that is actually an array containing the message public function sendMessage($registration_ids, $message) { $fields = array( 'registration_ids' => $registration_ids, 'data' => $message, ); //In this function we are calling the main method responsible for sending push notification //it is sendPushNotification return $this->sendPushNotification($fields); } //This is the main method responsible for sending push notification //I have already explained it in previous tutorials private function sendPushNotification($fields){ include_once __DIR__ . '/../../include/Config.php'; $url = 'https://android.googleapis.com/gcm/send'; $headers = array( 'Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); return $result; } } |
- Now come inside v1 folder and create a .htaccess file and write the following.
1 2 3 4 5 |
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L] |
- Finally in v1 folder create index.php this file will handle all the API calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
<?php require_once '../include/DbOperation.php'; require_once '../libs/gcm/gcm.php'; require '.././libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // User id from db - Global Variable $user_id = NULL; /** * User Registration * url - /register * method - POST * params - name, email */ $app->post('/register', function () use ($app) { //Verifying parameters verifyRequiredParams(array('name', 'email')); //Response array $response = array(); //Getting request parameters $name = $app->request->post('name'); $email = $app->request->post('email'); //Vaidating email validateEmail($email); //Creating a db object $db = new DbOperation(); //INserting user to database $res = $db->createUser($name, $email); //If user created //Adding the user detail to response if ($res == USER_CREATED_SUCCESSFULLY) { $response["error"] = false; $user = $db->getUser($email); $response['id'] = $user['id']; $response['name'] = $user['name']; $response['email'] = $user['email']; echoResponse(201, $response); //If user creating failes adding error to response } else if ($res == USER_CREATE_FAILED) { $response["error"] = true; $response["message"] = "Oops! An error occurred while registereing"; echoResponse(200, $response); //If user already exist //adding the user data to response } else if ($res == USER_ALREADY_EXISTED) { $response["error"] = false; $user = $db->getUser($email); $response['id'] = $user['id']; $response['name'] = $user['name']; $response['email'] = $user['email']; echoResponse(200, $response); } }); /* * URL: /send * Method: POST * parameters: id, message * */ //This is used to send message on the chat room $app->post('/send', function () use ($app) { //Verifying required parameters verifyRequiredParams(array('id', 'message')); //Getting request parameters $id = $app->request()->post('id'); $message = $app->request()->post('message'); $name = $app->request()->post('name'); //Creating a gcm object $gcm = new GCM(); //Creating db object $db = new DbOperation(); //Creating response array $response = array(); //Creating an array containing message data $pushdata = array(); //Adding title which would be the username $pushdata['title'] = $name; //Adding the message to be sent $pushdata['message'] = $message; //Adding user id to identify the user who sent the message $pushdata['id']=$id; //If message is successfully added to database if ($db->addMessage($id, $message)) { //Sending push notification with gcm object $gcm->sendMessage($db->getRegistrationTokens($id), $pushdata); $response['error'] = false; } else { $response['error'] = true; } echoResponse(200, $response); }); /* * URL: /storegcmtoken/:id * Method: PUT * Parameters: token * */ //This will store the gcm token to the database $app->put('/storegcmtoken/:id', function ($id) use ($app) { verifyRequiredParams(array('token')); $token = $app->request()->put('token'); $db = new DbOperation(); $response = array(); if ($db->storeGCMToken($id, $token)) { $response['error'] = false; $response['message'] = "token stored"; } else { $response['error'] = true; $response['message'] = "Could not store token"; } echoResponse(200, $response); }); /* * URL: /messages * Method: GET * */ //This will fetch all the messages available on the database to display on the thread $app->get('/messages', function () use ($app){ $db = new DbOperation(); $messages = $db->getMessages(); $response = array(); $response['error']=false; $response['messages'] = array(); while($row = mysqli_fetch_array($messages)){ $temp = array(); $temp['id']=$row['id']; $temp['message']=$row['message']; $temp['userid']=$row['users_id']; $temp['sentat']=$row['sentat']; $temp['name']=$row['name']; array_push($response['messages'],$temp); } echoResponse(200,$response); }); //Function to validate email function validateEmail($email) { $app = \Slim\Slim::getInstance(); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $response["error"] = true; $response["message"] = 'Email address is not valid'; echoResponse(400, $response); $app->stop(); } } //Function to display the response in browser function echoResponse($status_code, $response) { $app = \Slim\Slim::getInstance(); // Http response code $app->status($status_code); // setting response content type to json $app->contentType('application/json'); echo json_encode($response); } //Function to verify required parameters function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $request_params = $_REQUEST; // Handling PUT request params if ($_SERVER['REQUEST_METHOD'] == 'PUT') { $app = \Slim\Slim::getInstance(); parse_str($app->request()->getBody(), $request_params); } foreach ($required_fields as $field) { if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { $error = true; $error_fields .= $field . ', '; } } if ($error) { // Required field(s) are missing or empty // echo error json and stop the app $response = array(); $app = \Slim\Slim::getInstance(); $response["error"] = true; $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; echoResponse(400, $response); $app->stop(); } } function authenticate(\Slim\Route $route) { //Implement authentication if needed } $app->run(); |
- Thats it for the API Coding. Now you need a REST Client to Test the API. You can use Postman for google chrome.
Testing the API
- You can use Postman for chrome or any other REST Client to test your API. The final API we built is shown in the following table
Base URL: http://localhost/SimplifiedCodingChat/v1/
URL | Method | Parameters |
---|---|---|
register | POST | name,email |
send | POST | id, message |
storegcmtoken/:id | PUT | token |
messages | GET |
- If you are having some problems or troubles you can get my php project for this Android Chat App for Android Tutorial from the link given below (You need to unlock the link).
[sociallocker id=1372]Â Download REST API Project[/sociallocker]
So thats all for this part friends. You can follow the next part from the link given.
Create Chat Application in Android using GCM Part 2
In this part we will actually Create Chat App for Android using Android Studio. And yes feel free to ask by comments if having any troubles. Thank You 🙂