Sei sulla pagina 1di 11

Chat App using Firebase

LoginActivity
package com.apkglobal.chatapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
TextView tv_registerUser;
EditText et_username, et_password;
Button loginButton;
String user, pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
// typecasting of different elements
tv_registerUser = (TextView) findViewById(R.id.register);
et_username = (EditText) findViewById(R.id.username);
et_password = (EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.loginButton);
// click event on Register Button
tv_registerUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
// click event on Login Button
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Getting user & pass into string from editText
user = et_username.getText().toString();
pass = et_password.getText().toString();
//Condition for user inputs
if (user.equals("")) {
et_username.setError("can't be blank");
} else if (pass.equals("")) {
et_password.setError("can't be blank");
} else {
// url to get data from server
String url = "https://chatapp-2429a.firebaseio.com/users.json";
// progress dialog for user Authentication
final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
pd.setMessage("Loading...");
pd.show();
// Get user data from server
StringRequest request = new StringRequest(Request.Method.GET, url, new
Response.Listener<String>() {
@Override
public void onResponse(String s) {
if (s.equals("null")) {
Toast.makeText(LoginActivity.this, "user not found",
Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
if (!obj.has(user)) {
Toast.makeText(LoginActivity.this, "user not found",
Toast.LENGTH_LONG).show();
}
/*checking user and pass from server
* put user and pass into userDetails class
* */
else if (obj.getJSONObject(user).getString("password").equals(pass)) {
UserDetails.username = user;
UserDetails.password = pass;
startActivity(new Intent(LoginActivity.this, UserActivity.class));
}
else {
Toast.makeText(LoginActivity.this, "incorrect password",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// dismiss progress dialog
pd.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
pd.dismiss();
}
});
RequestQueue rQueue = Volley.newRequestQueue(LoginActivity.this);
rQueue.add(request);
}
}
});
}
}

RegisterActivity
package com.apkglobal.chatapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.firebase.client.Firebase;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
EditText et_username, et_password;
Button registerButton;
String user, pass;
TextView login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().hide();
et_username = (EditText) findViewById(R.id.username);
et_password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.registerButton);
login = (TextView) findViewById(R.id.login);
Firebase.setAndroidContext(this);
// clicklistener for login text view
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
// clicklistener for register button
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// getting user inputs into string
user = et_username.getText().toString();
pass = et_password.getText().toString();
// security features for user input
if (user.equals("")) {
et_username.setError("can't be blank");
} else if (pass.equals("")) {
et_password.setError("can't be blank");
}
else if (!user.matches("[A-Za-z0-9]+")) {
et_username.setError("only alphabet or number allowed");
}
else if (user.length() < 5) {
et_username.setError("at least 5 characters long");
}
else if (pass.length() < 5) {
et_password.setError("at least 5 characters long");
}
else {
final ProgressDialog pd = new ProgressDialog(RegisterActivity.this);
pd.setMessage("Loading...");
pd.show();
// Volley initialization
String url = "https://chatapp-2429a.firebaseio.com/users.json";
// Stringrequest method to send data to the api
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new
Response.Listener<String>() {
@Override
// Response handling method in volley
public void onResponse(String s) {
Firebase reference = new Firebase("https://chatapp-2429a.firebaseio.com/users");
/*
* checks if
* */
if (s.equals("null")) {
reference.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful",
Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
//
// if user is not present then create new user
if (!obj.has(user)) {
reference.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful",
Toast.LENGTH_LONG).show();
// check if user is already present then make toast
} else {
Toast.makeText(RegisterActivity.this, "username already
exists", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
pd.dismiss();
}
// Error handling method in volley
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("some error occured" + error);
pd.dismiss();
}
});
// creating request queue for execution
RequestQueue rQueue = Volley.newRequestQueue(RegisterActivity.this);
rQueue.add(stringRequest);
}
}
});
}
}

UserActivity
package com.apkglobal.chatapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
public class UserActivity extends AppCompatActivity {
ListView usersList;
TextView noUsersText;
ArrayList<String> myarrayList = new ArrayList<>();
int totalUsers = 0;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
usersList = (ListView)findViewById(R.id.usersList);
noUsersText = (TextView)findViewById(R.id.noUsersText);
pd = new ProgressDialog(UserActivity.this);
pd.setMessage("Loading...");
pd.show();
String url = "https://chatapp-2429a.firebaseio.com/users.json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
@Override
public void onResponse(String s) {
doOnSuccess(s);
}
},new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
}
});
RequestQueue rQueue = Volley.newRequestQueue(UserActivity.this);
rQueue.add(request);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserDetails.chatWith = myarrayList.get(position);
startActivity(new Intent(UserActivity.this, ChatActivity.class));
}
});
}
public void doOnSuccess(String s){
try {
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String mykey = "";
while(i.hasNext()){
mykey = i.next().toString();
if(!mykey.equals(UserDetails.username)) {
myarrayList.add(mykey);
}
totalUsers++;
}
} catch (JSONException e) {
e.printStackTrace();
}
if(totalUsers <=1){
noUsersText.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
}
else{
noUsersText.setVisibility(View.GONE);
usersList.setVisibility(View.VISIBLE);
usersList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myarrayList));
}
pd.dismiss();
}
}

ChatActivity
package com.apkglobal.chatapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import java.util.HashMap;
import java.util.Map;
public class ChatActivity extends AppCompatActivity {
LinearLayout layout;
RelativeLayout layout_2;
ImageView sendButton;
EditText messageArea;
ScrollView scrollView;
Firebase reference1, reference2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
layout = (LinearLayout) findViewById(R.id.layout1);
layout_2 = (RelativeLayout)findViewById(R.id.layout2);
sendButton = (ImageView)findViewById(R.id.sendButton);
messageArea = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
Firebase.setAndroidContext(this);
reference1 = new Firebase("https://chatapp-2429a.firebaseio.com/messages/" + UserDetails.username + "_" +
UserDetails.chatWith);
reference2 = new Firebase("https://chatapp-2429a.firebaseio.com/messages/" + UserDetails.chatWith + "_" +
UserDetails.username);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
if(!messageText.equals("")){
Map<String, String> map = new HashMap<String, String>();
map.put("message", messageText);
map.put("user", UserDetails.username);
reference1.push().setValue(map);
reference2.push().setValue(map);
messageArea.setText("");
}
}
});
reference1.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("user").toString();
if(userName.equals(UserDetails.username)){
addMessageBox("You:-\n" + message, 1);
}
else{
addMessageBox(UserDetails.chatWith + ":-\n" + message, 2);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
public void addMessageBox(String message, int type){
TextView textView = new TextView(ChatActivity.this);
textView.setText(message);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.weight = 1.0f;
if(type == 1) {
lp2.gravity = Gravity.LEFT;

//textView.setBackgroundResource(R.drawable.bubble_in);
}
else{
lp2.gravity = Gravity.RIGHT;

//textView.setBackgroundResource(R.drawable.bubble_out);
}
textView.setLayoutParams(lp2);
layout.addView(textView);
scrollView.fullScroll(View.FOCUS_DOWN);
}
}

UserDetails (Helper class)


package com.apkglobal.chatapp;
/**
* Created by prince on 20/6/17.
*/
public class UserDetails {
/*user data from the server
*
* */
static String username = "";
static String password = "";
static String chatWith = "";
}

XML files

activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:background="#f7f2eb"
android:padding="16dp"
android:gravity="center"
tools:context="com.apkglobal.chatapp.LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="30dp"
android:gravity="center"
android:layout_marginBottom="20dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:backgroundTint="#fff"
android:background="@drawable/login_border"
android:id="@+id/username"
android:inputType="text"
android:maxLines="1"
android:hint="Enter Username"
android:layout_marginBottom="10dp"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/login_border"
android:backgroundTint="#fff"
android:hint="Enter Password"
android:inputType="textPassword"
android:maxLines="1"
android:padding="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textColor="#fff"
android:backgroundTint="#837089"
android:id="@+id/loginButton"
android:layout_marginBottom="20dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click here to register"
android:textSize="20dp"
android:gravity="center"
android:id="@+id/register"/>
</LinearLayout>

activity_register.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7f2eb"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.apkglobal.chatapp.RegisterActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:gravity="center"
android:text="Register"
android:textSize="30dp" />
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/login_border"
android:backgroundTint="#fff"
android:hint="Enter Username"
android:inputType="text"
android:maxLines="1"
android:padding="10dp" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/login_border"
android:backgroundTint="#fff"
android:hint="Enter Password"
android:inputType="textPassword"
android:maxLines="1"
android:padding="10dp" />
<Button
android:id="@+id/registerButton"
android:layout_width="match_parent"
android:textColor="#fff"
android:backgroundTint="#837089"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="Register" />
<TextView
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Click here to login"
android:textSize="20dp" />
</LinearLayout>

activity_user.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7f2eb"
android:orientation="vertical"
tools:context="com.apkglobal.chatapp.UserActivity">
<TextView
android:id="@+id/noUsersText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No users found!"
android:visibility="gone" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Available Users"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"/>
<ListView
android:id="@+id/usersList"
android:layout_width="match_parent"
android:listSelector="#c5c5c5"
android:layout_height="wrap_content" />
</LinearLayout>

activity_chat.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#f7f2eb"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.apkglobal.chatapp.ChatActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_weight="20"
android:padding="10dp"
android:layout_height="wrap_content"
android:id="@+id/scrollView">
<RelativeLayout
android:id="@+id/layout2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/layout1">
</LinearLayout>
</RelativeLayout>
</ScrollView>
<include
layout="@layout/message_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_marginTop="5dp"/>
</LinearLayout>

message_area.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<EditText
android:id="@+id/messageArea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:background="@drawable/border"
android:hint="Write a message..."
android:maxHeight="80dp"
android:padding="8dp"
android:textColor="#000"
android:textColorHint="#bdbdbd" />
<ImageView
android:id="@+id/sendButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"
android:layout_marginBottom="5dp"
android:padding="4dp"
android:tint="#000"
android:src="@android:drawable/ic_menu_send" />
</LinearLayout>

Add dependency in build.gradle file


compile 'com.firebase:firebase-client-android:2.5.2+'

compile 'com.android.volley:volley:1.0.0'
compile 'com.google.firebase:firebase-messaging:11.0.1'

Potrebbero piacerti anche