<file_sep>package com.example.hp.firechat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;

import java.util.HashMap;

public class RegisterActivity extends AppCompatActivity {
    private EditText mDisplayName;
    private EditText mEmail;
    private EditText mPassword;
    private Button mCreateBtn;
    private ProgressDialog PD;
    private FirebaseAuth mAuth;
    private Toolbar mToolbar;
    FirebaseUser current_user;
    private DatabaseReference mDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_register);
            mDisplayName = (EditText) findViewById(R.id.nameField);
            mEmail = (EditText) findViewById(R.id.emailField);
            mPassword = (EditText) findViewById(R.id.passwordField);
            mCreateBtn = (Button) findViewById(R.id.registerBtn);
            mAuth = FirebaseAuth.getInstance();
            current_user = FirebaseAuth.getInstance().getCurrentUser();
            mToolbar = (Toolbar) findViewById(R.id.register_toolbar);
            PD = new ProgressDialog(RegisterActivity.this);
            setSupportActionBar(mToolbar);
            getSupportActionBar().setTitle("Create Account");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mCreateBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        final String name = mDisplayName.getText().toString().trim();
                        final String email = mEmail.getText().toString().trim();
                        final String password = mPassword.getText().toString().trim();
                        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
                                PD.setMessage("signing up");
                                PD.setIndeterminate(false);
                                PD.setCanceledOnTouchOutside(false);
                                PD.setCancelable(true);
                                PD.show();

                            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {
                                        current_user = FirebaseAuth.getInstance().getCurrentUser();
                                        if(current_user!=null) {
                                            String uid = current_user.getUid();
                                            String device_token= FirebaseInstanceId.getInstance().getToken();
                                            mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
                                            mDatabase.child("name").setValue(name);
                                            mDatabase.child("status").setValue("hi there I am using FireChat");
                                            mDatabase.child("image").setValue("default");
                                            mDatabase.child("thumb_image").setValue("default");
                                            mDatabase.child("device_token").setValue(device_token);
                                   /* HashMap<String, String> userMap = new HashMap<>();
                                    userMap.put("name", name);
                                    userMap.put("status", "hi there I am using FireChat");
                                    userMap.put("image", "default");
                                    userMap.put("thumb_image", "default");*/
                                            Toast.makeText(getApplicationContext(), "uploading is successful", Toast.LENGTH_SHORT).show();
                                            Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
                                            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                            startActivity(mainIntent);
                                            if (PD.isShowing()) {
                                                PD.dismiss();
                                            }
                                        }
                                    } else {
                                        Toast.makeText(getApplicationContext(), "uploading is not successful", Toast.LENGTH_SHORT).show();
                                        if (PD.isShowing()) {
                                            PD.dismiss();
                                        }
                                    }
                                }
                            });

                        } else {
                            Toast.makeText(getApplicationContext(), "PLEASE ENTER THE FIELDS", Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            });
    }

}
<file_sep>package com.example.hp.firechat;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;

public class StatusActivity extends AppCompatActivity {
    private Button changeBtn;
    private EditText status;
    private Toolbar status_Tool;
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private ProgressDialog PD;
    private String uid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_status);
        changeBtn=(Button)findViewById(R.id.changeBtn);
        status=(EditText)findViewById(R.id.Date_text);
        status_Tool=(Toolbar) findViewById(R.id.status_toolbar);
        setSupportActionBar(status_Tool);
        getSupportActionBar().setTitle("Change status");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mAuth=FirebaseAuth.getInstance();
        mDatabase= FirebaseDatabase.getInstance().getReference().child("Users");
         uid=mAuth.getCurrentUser().getUid();
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String statusBro=dataSnapshot.child(uid).child("status").getValue().toString();
                status.setText(statusBro);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        changeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String status_changed = status.getText().toString();
                if(!TextUtils.isEmpty(status_changed)) {
                         /*   if(PD == null){
                                PD = new ProgressDialog(StatusActivity.this);
                                PD.setMessage("please wait..");
                                PD.setIndeterminate(false);
                                PD.setCancelable(true);
                                PD.show();
                            } */
                    mDatabase.child(uid).child("status").setValue(status_changed);
                    Intent SettingsIntent = new Intent(StatusActivity.this, SettingsActivity.class);
                    // SettingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    // SettingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(SettingsIntent);
                    Toast.makeText(getApplicationContext(), "status is updated", Toast.LENGTH_SHORT).show();
                          /*  if(PD.isShowing()){
                                PD.dismiss();
                            } */
                }
                else{
                    Toast.makeText(getApplicationContext(), "Please enter the field", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
    @Override
    protected void onResume(){
        super.onResume();
        Log.e("ajay123","wow1");
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser!=null) {
            mDatabase.child(currentUser.getUid()).child("online").setValue("true");
            // mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("ajay124","wow2");
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser!=null) {
            mDatabase.child(currentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
            // mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
        }
    }
}
<file_sep>package com.example.hp.firechat;

/**
 * Created by hp on 12/9/2017.
 */

public class ChatsFrag {
    public String date;
    public ChatsFrag(){
    }
    public ChatsFrag(String date){
        this.date=date;
    }
    public String getDate(){
        return date;
    }
    public void setDate(String date){
        this.date=date;
    }
}
<file_sep>package com.example.hp.firechat;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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

public class FutureMessagingActivity extends AppCompatActivity {
    private Toolbar status_Tool;
    private EditText DateText;
    private EditText TimeText;
    private EditText MessageText;
    private Button OkayBtn;
    private String mChatUser;
    private String mChatUsername;
    private DatabaseReference mMessagesDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_future_messaging);
        status_Tool=(Toolbar) findViewById(R.id.future_app_toolbar);
        setSupportActionBar(status_Tool);
        getSupportActionBar().setTitle("Change status");
       // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        DateText=(EditText)findViewById(R.id.Date_text);
        TimeText=(EditText)findViewById(R.id.Time_text);
        OkayBtn=(Button)findViewById(R.id.okay_button);
        MessageText=(EditText)findViewById(R.id.future_Message);
        mChatUser = getIntent().getStringExtra("current_user");
        mChatUsername = getIntent().getStringExtra("user_key");
        mMessagesDatabase= FirebaseDatabase.getInstance().getReference().child("FutureMessages");
        OkayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String Date = DateText.getText().toString();
                    String Time = TimeText.getText().toString();
                    final String message = MessageText.getText().toString();
                    if (!TextUtils.isEmpty(Date) && !TextUtils.isEmpty(Time) && !TextUtils.isEmpty(message)) {
                        if (Date.length() == 10 && Time.length() == 8) {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            java.util.Date date3 = null;
                            try {
                                date3 = dateFormat.parse(Date + " " + Time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            final long unixTime3 = (long) date3.getTime();
                            Log.e("database", "ajay" + unixTime3);
                            Log.e("database", "vijay" + System.currentTimeMillis());


                            mMessagesDatabase.child(mChatUsername).child(mChatUser).child("type").setValue("going").addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        mMessagesDatabase.child(mChatUsername).child(mChatUser).child("message").setValue(message);
                                        mMessagesDatabase.child(mChatUsername).child(mChatUser).child("ftimestamp").setValue(unixTime3);
                                        mMessagesDatabase.child(mChatUsername).child(mChatUser).child("timestamp").setValue(System.currentTimeMillis());
                                        mMessagesDatabase.child(mChatUser).child(mChatUsername).child("timestamp").setValue(System.currentTimeMillis());
                                        mMessagesDatabase.child(mChatUser).child(mChatUsername).child("type").setValue("coming");
                                        mMessagesDatabase.child(mChatUser).child(mChatUsername).child("message").setValue(message);
                                        mMessagesDatabase.child(mChatUser).child(mChatUsername).child("ftimestamp").setValue(unixTime3).addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (!task.isSuccessful()) {
                                                    Toast.makeText(getApplicationContext(), "failed to add it ", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    Toast.makeText(getApplicationContext(), "Added to the database ", Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });
                                    }

                                }
                            });
                        } else {
                            Toast.makeText(getApplicationContext(), "please enter correct inputs", Toast.LENGTH_SHORT).show();

                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "Please enter the fields", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });


    }
    @Override

    protected void onResume() {

        super.onResume();//visible

        Log.d("resume11","Activity resumed");

    }

    @Override

    protected void onPause() {

        super.onPause();//invisible

        Log.d("resume12", "Activity paused");
    }
}
<file_sep>package com.example.hp.firechat;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.*;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TimeZone;

import de.hdodenhof.circleimageview.CircleImageView;

public class GoodChatActivity extends AppCompatActivity {
    private String mChatUser;
    private Toolbar chat_Tool_bar;
    private DatabaseReference mRootRef;
    private String mChatUsername;
    private TextView mTitleView;
    private TextView mLastSeenView;
    private CircleImageView mProfileImage;
    private FirebaseAuth mAuth;
    private String mCurrentUserId;
    private ImageButton mChatAddBtn;
    private ImageButton mChatSendBtn;
    private EditText mChatMsgView;
    private RecyclerView mMessagesList;
    // private SwipeRefreshLayout mRefreshLayout;
     private final List<Messages> messagesList=new ArrayList<>();
    private LinearLayoutManager mLinearLayout;
    // private MessageAdapter mAdapter;
    private DatabaseReference mMessageDatabase;
    private static final int Total_items_to_load=10;
    private int mCurrentPage=1;
    private int itempos=0;
    private String mLastKey="";
    private String mPrevKey="";
    private DatabaseReference mFutureReference;
    private DatabaseReference mMessagesReference;
    private DatabaseReference mMessages;
    private DatabaseReference mDatabase;
    private String watching;
    private String image,imageUser;
    private int watch;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_chat);
        mChatUser = getIntent().getStringExtra("Blog_id");
       // watching=getIntent().getStringExtra("watch");
      //  Toast.makeText(getApplicationContext(), watching, Toast.LENGTH_SHORT).show();
      //  watch=Integer.parseInt(watching);
      //  Toast.makeText(getApplicationContext(),mChatUser, Toast.LENGTH_SHORT).show();
        //  mChatUsername = getIntent().getStringExtra("user_name");
        mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_Btn);
        mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_Btn);
        mChatMsgView = (EditText) findViewById(R.id.chat_view_EditText);
        mAuth = FirebaseAuth.getInstance();
        mCurrentUserId = mAuth.getCurrentUser().getUid();
        chat_Tool_bar = (Toolbar) findViewById(R.id.chat_tool_bar_bro);
        setSupportActionBar(chat_Tool_bar);
        //setting the adapter
        //from there to here
        mRootRef = FirebaseDatabase.getInstance().getReference();
        mRootRef.child("Messages").keepSynced(true);
        // getSupportActionBar().setTitle(mChatUsername);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowCustomEnabled(true);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View action_bar_view = inflater.inflate(R.layout.chat_custom_bar, null);
        actionBar.setCustomView(action_bar_view);

        mMessagesList = (RecyclerView) findViewById(R.id.messages_list2);
        mLinearLayout = new LinearLayoutManager(GoodChatActivity.this);
        mMessagesList.setHasFixedSize(true);
        mMessagesList.setLayoutManager(mLinearLayout);
        mTitleView = (TextView) findViewById(R.id.custom_display_name);
        mLastSeenView = (TextView) findViewById(R.id.custom_last_seen);
        mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
        // mTitleView.setText(mChatUsername);
        //setting the adapter
        // mAdapter = new MessageAdapter(messagesList);


        // mMessagesList.setAdapter(mAdapter);
        //  mRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.message_swipe_layout);
        mFutureReference=FirebaseDatabase.getInstance().getReference().child("FutureMessages");
        mMessagesReference=FirebaseDatabase.getInstance().getReference().child("Messages");
        mDatabase=FirebaseDatabase.getInstance().getReference().child("Users");
        mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long k=dataSnapshot.getChildrenCount();
                mRootRef.child("seenMsgs").child(mCurrentUserId).child(mChatUser).child("seen").setValue(k).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if(task.isSuccessful()){
                           // Toast.makeText(getApplicationContext(),"computed succesfully", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Toast.makeText(getApplicationContext(),"computed unsuccesfully", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

        //loadMessages();
        //from there to here
        mDatabase.child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                imageUser=dataSnapshot.child("image").getValue().toString();                      //
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild("online")) {
                    String online = dataSnapshot.child("online").getValue().toString();
                    image = dataSnapshot.child("image").getValue().toString();                  //
                    String name=dataSnapshot.child("name").getValue().toString();
                    mTitleView.setText(name);
                    if (online.equals("true")) {
                        mLastSeenView.setText("online");
                    } else {
                        GetTimeAgo getTimeAgo = new GetTimeAgo();
                        Long lastTime = Long.parseLong(online);
                        String LastSeenTime = getTimeAgo.getTimeAgo(lastTime, GoodChatActivity.this);
                        mLastSeenView.setText(LastSeenTime);
                    }
                    if(!image.equals("default")) {
                        Picasso.with(GoodChatActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mProfileImage, new Callback() {
                            @Override
                            public void onSuccess() {

                            }

                            @Override
                            public void onError() {
                                Picasso.with(GoodChatActivity.this).load(image).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mProfileImage);
                            }
                        });
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (!dataSnapshot.hasChild(mChatUser)) {
                    mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue("false").addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) {
                            if (task.isSuccessful()) {
                                mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("timestamp").setValue(ServerValue.TIMESTAMP);
                                mRootRef.child("Chat").child(mChatUser).child(mCurrentUserId).child("timestamp").setValue(ServerValue.TIMESTAMP);
                                mRootRef.child("Chat").child(mChatUser).child(mCurrentUserId).child("seen").setValue("false");

                            }
                        }
                    });
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        mChatSendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }


        });
        mChatAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent FutureMessaging = new Intent(GoodChatActivity.this, FutureMessagingActivity.class);
                //     Toast.makeText(getApplicationContext(),"going to loginactivity", Toast.LENGTH_SHORT).show();
                //loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                FutureMessaging.putExtra("current_user",mCurrentUserId);
                FutureMessaging.putExtra("user_key",mChatUser);
                startActivity(FutureMessaging);
                //finish();
            }
        });


    }
    private void sendMessage() {
        try {
            final String message = mChatMsgView.getText().toString();
            if (!TextUtils.isEmpty(message)) {
                final DatabaseReference current_user_ref = mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser);
                final DatabaseReference chat_user_ref = mRootRef.child("Messages").child(mChatUser).child(mCurrentUserId);
                DatabaseReference user_msg_push = mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser).push();
                final String push_id_user = user_msg_push.getKey();
                current_user_ref.child(push_id_user).child("message").setValue(message).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            current_user_ref.child(push_id_user).child("seen").setValue("false");
                            current_user_ref.child(push_id_user).child("type").setValue("text");
                            current_user_ref.child(push_id_user).child("from").setValue(mCurrentUserId);
                            current_user_ref.child(push_id_user).child("time").setValue(System.currentTimeMillis());
                            chat_user_ref.child(push_id_user).child("time").setValue(System.currentTimeMillis());
                            chat_user_ref.child(push_id_user).child("from").setValue(mCurrentUserId);
                            chat_user_ref.child(push_id_user).child("message").setValue(message);
                            chat_user_ref.child(push_id_user).child("seen").setValue("false");
                            chat_user_ref.child(push_id_user).child("type").setValue("text");
                            mChatMsgView.setText("");
                            current_user_ref.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    long k=dataSnapshot.getChildrenCount();
                                    mMessagesList.scrollToPosition((int)k -1);
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });
                            Toast.makeText(getApplicationContext(), "Message is sent successfully", Toast.LENGTH_SHORT).show();

                        }
                    }
                });


            } else {
                Toast.makeText(getApplicationContext(), "Please enter any message", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    @Override
    public   void onStart() {
        super.onStart();
        mMessages = FirebaseDatabase.getInstance().getReference().child("Messages").child(mCurrentUserId).child(mChatUser);
        FirebaseRecyclerAdapter<GoodChat,GoodChatActivity.ChatViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<GoodChat, GoodChatActivity.ChatViewHolder>(
                GoodChat.class,
                R.layout.message_single_layout,
                GoodChatActivity.ChatViewHolder.class,
                mMessages
        ) {
            @Override
            protected void populateViewHolder(final GoodChatActivity.ChatViewHolder chatViewHolder, GoodChat chats, int position) {
               try {
                    final String user_key = getRef(position).getKey();int i=0;
                    String current_user_id = mAuth.getCurrentUser().getUid();
                    String from_user = chats.getFrom();
                    // viewHolder.settings(from_user,current_user_id);
                    chatViewHolder.mMessageText.setText(chats.getMessage());
                  // ChatViewHolder.settings(time);


                    mDatabase.child(from_user).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            chatViewHolder.mMessageName.setText(dataSnapshot.child("name").getValue().toString());

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });
                   mRootRef.child("Messages").child(mCurrentUserId).child(mChatUser).child(user_key).addValueEventListener(new ValueEventListener() {
                       @Override
                       public void onDataChange(DataSnapshot dataSnapshot) {
                           int i=0;
                           long time= Long.parseLong(dataSnapshot.child("time").getValue().toString());
                           String[] st=new String[3];
                           Date date = new Date(time);
                           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
                           sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); // give a timezone reference for formating (see comment at the bottom
                           String formattedDate = sdf.format(date);
                           StringTokenizer str=new StringTokenizer(formattedDate," ");
                           while(str.hasMoreElements()){
                               st[i++]=str.nextToken();
                           }
                           chatViewHolder.mTime.setText(st[1]);
                           i=0;
                       }

                       @Override
                       public void onCancelled(DatabaseError databaseError) {

                       }
                   });
                    if (current_user_id.equals(from_user)) {
                        chatViewHolder.mMessageText.setBackgroundColor(Color.WHITE);
                        //  Toast.makeText(getClass(),"uploading thumbnail2 is failed", Toast.LENGTH_SHORT).show();
                        Log.d("one", "current user id");

                        chatViewHolder.mMessageText.setTextColor(Color.BLACK);

                    } else {
                        chatViewHolder.mMessageText.setBackgroundResource(R.drawable.message_text_background);

                        chatViewHolder.mMessageText.setTextColor(Color.WHITE);

                    }


                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        };
        mMessagesList.setAdapter(firebaseRecyclerAdapter);
        mMessages.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                final long num = dataSnapshot.getChildrenCount();
                mMessagesList.scrollToPosition((int)num-1);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
    public static class ChatViewHolder extends RecyclerView.ViewHolder{
        public  TextView mMessageText;
        public TextView mMessageName;
        public static CircleImageView profileImage;
        public  TextView mTime;
        View mView;
        public ChatViewHolder(View view){
            super(view);
            mView=view;
            mMessageText=(TextView)view.findViewById(R.id.message_text_layout);
            profileImage=(CircleImageView)view.findViewById(R.id.message_profile_layout);
            mMessageName=(TextView)view.findViewById(R.id.message_name_layout);
            mTime=(TextView)view.findViewById(R.id.message_time_layout);
        }

        public static void settings(long time) {
            long timer=time;int i=0;
            String[] st=new String[3];
            Date date = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); // give a timezone reference for formating (see comment at the bottom
            String formattedDate = sdf.format(date);
            StringTokenizer str=new StringTokenizer(formattedDate," ");
                while(str.hasMoreElements()){
                    st[i++]=str.nextToken();
                }
              //  mTime.setText(st[1]);
            // System.out.println(formattedDate);
            // Log.d("time 5","ajay2 "+formattedDate);

        }
    }
    @Override
    protected void onResume(){
        super.onResume();
        Log.e("ajay123","wow1");
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser!=null) {
            mDatabase.child(currentUser.getUid()).child("online").setValue("true");
            // mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("ajay124","wow2");
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser!=null) {
            mDatabase.child(currentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
            // mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
        }
    }


}
<file_sep>package com.example.hp.firechat;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private FirebaseUser CurrentUser,mCurrentUser;
    private Toolbar mToolbar;
    private SectionPageAdapter mSectionPagerAdapter;
    private ViewPager mViewPager;
    private TabLayout mTablayout;
   private DatabaseReference mDatabase;
   //private FirebaseUser mCurrentUser;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       try {
            setContentView(R.layout.activity_main);
            mAuth = FirebaseAuth.getInstance();
            mCurrentUser=mAuth.getCurrentUser();
            mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
            setSupportActionBar(mToolbar);
            getSupportActionBar().setTitle("Fire Chat");
            if(mCurrentUser!=null) {
                mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
            }
            //getting the tabs
            mViewPager = (ViewPager) findViewById(R.id.main_tabPager);
            mSectionPagerAdapter = new SectionPageAdapter(getSupportFragmentManager());
            mViewPager.setAdapter(mSectionPagerAdapter);
            mTablayout = (TabLayout) findViewById(R.id.main_tabs);
            mTablayout.setupWithViewPager(mViewPager);
           // threadBro();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        CurrentUser=mAuth.getCurrentUser();
        if(CurrentUser==null){
            Intent loginIntent = new Intent(MainActivity.this, StartActivity.class);
            //     Toast.makeText(getApplicationContext(),"going to loginactivity", Toast.LENGTH_SHORT).show();
            loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(loginIntent);
            finish();
        }
       else{
           // Toast.makeText(getApplicationContext(),"there is some person who logged in", Toast.LENGTH_SHORT).show();
            try {
                 mDatabase.child(CurrentUser.getUid()).child("online").setValue("true");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

   /* @Override
    protected void onStop() {
        super.onStop();
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser!=null) {
            mDatabase.child(CurrentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
           // mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
        }
    } */

     @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main_menu,menu);


         return true;
    }
     @Override
    public boolean onOptionsItemSelected(MenuItem item) {

         if (item.getItemId() == R.id.settings_btn) {
            //Toast.makeText(getApplicationContext(),"entered", Toast.LENGTH_SHORT).show();
            //startActivity(new Intent(MainActivity.this,Post_activity.class));
            try {
                Intent RegisterIntent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(RegisterIntent);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (item.getItemId() == R.id.users_btn) {
            Intent UsersIntent = new Intent(MainActivity.this, UsersActivity.class);
            startActivity(UsersIntent);
        }
        if (item.getItemId() == R.id.main_logout_btn) {
            mAuth.signOut();
            mDatabase.child(CurrentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
            Intent loginIntent = new Intent(MainActivity.this, StartActivity.class);
            //     Toast.makeText(getApplicationContext(),"going to loginactivity", Toast.LENGTH_SHORT).show();
            loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(loginIntent);
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
    public void threadBro()
    {

        Runnable runnable = new Runnable() {
            public void run() {
               // Toast.makeText(getApplicationContext(),"thread is running ra", Toast.LENGTH_SHORT).show();
                long endTime = System.currentTimeMillis()
                        + 20*1000;

                while (System.currentTimeMillis() < endTime) {
                    synchronized (this) {
                        try {
                            Log.d("thread","thread is executing");
                            wait(endTime -
                                    System.currentTimeMillis());
                        } catch (Exception e) {}
                    }
                }
            }
        };
        Thread mythread = new Thread(runnable);
        mythread.start();
    }
    @Override
    protected void onResume(){
        super.onResume();
        Log.e("ajay1","wow1");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("ajay2","wow2");
        FirebaseUser currentUser=mAuth.getCurrentUser();
        if(currentUser!=null) {
            mDatabase.child(CurrentUser.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
            // mDatabase.child(CurrentUser.getUid()).child("LastSeen").setValue(ServerValue.TIMESTAMP);
        }
    }
}
class Task implements Runnable{
    public void run(){
        for(int i=0;i<2;i++)
        Log.d("thread1","thread is executing");
    }
}
class MyAndroidThread implements Runnable
{
    Activity activity;
    public MyAndroidThread(Activity activity)
    {
        this.activity = activity;
    }
    @Override
    public void run()
    {
        /*activity.runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {


            }
        });*/
        long endTime = System.currentTimeMillis()
                + 5*1000;

        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    Log.d("thread","thread is executing");
                   // Toast.makeText(activity,"thread is running in class with correct time", Toast.LENGTH_SHORT).show();

                   // Thread.sleep(endTime-System.currentTimeMillis());
                     wait(endTime -
                            System.currentTimeMillis());
                   // Toast.makeText(activity,"thread is running in class with correct time", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {}
            }
        }
    }

}
<file_sep>package com.example.hp.firechat;

import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by hp on 11/19/2017.
 */

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage){
        super.onMessageReceived(remoteMessage);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(FirebaseMessagingService.this,"ajay");
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setContentTitle("My Friend Request");
        mBuilder.setContentText("You have received a new request");
        // Sets an ID for the notification
        int mNotificationId = (int) System.currentTimeMillis();
// Gets an instance of the NotificationManager service
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
        mNotifyMgr.notify(mNotificationId, mBuilder.build());

    }
}
<file_sep>package com.example.hp.firechat;

/**
 * Created by hp on 11/23/2017.
 */

public class Messages {
    private String message,seen,type,from;
    private long time;
    public Messages(){

    }
    public Messages(String message,String seen,long time,String type,String from){
        this.message=message;
        this.seen=seen;
        this.time=time;
        this.type=type;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message){
        this.message=message;
    }
    public String getSeen(){
        return seen;
    }
    public void setSeen(String seen){
        this.seen=seen;
    }
    public long getTime(){
        return time;
    }
    public void setTime(long time){
        this.time=time;
    }
    public String getType(){
        return type;
    }
    public void setType(String type){
        this.type=type;
    }
    public String getFrom(){
        return from;
    }
    public void setFrom(String from){
        this.from=from;
    }

}
<file_sep>package com.example.hp.firechat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;

public class LoginActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private EditText mLoginEmail;
    private EditText mLoginPassword;
    private Button mSignUpbtn;
    private FirebaseAuth mAuth;
    private ProgressDialog PD;
    private DatabaseReference mDatabaseUsers;
    private String current_user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mToolbar=(Toolbar)findViewById(R.id.Login_toolbar);
        mLoginEmail=(EditText)findViewById(R.id.emailField);
        mLoginPassword=(EditText)findViewById(R.id.passwordField);
        mSignUpbtn=(Button)findViewById(R.id.SignUpBtn);
        PD = new ProgressDialog(LoginActivity.this);
        mDatabaseUsers= FirebaseDatabase.getInstance().getReference().child("Users");
        mAuth=FirebaseAuth.getInstance();
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Login");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mSignUpbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email=mLoginEmail.getText().toString().trim();
                String password=mLoginPassword.getText().toString().trim();

                if(!TextUtils.isEmpty(email)&&(!TextUtils.isEmpty(password)))
                {
                    PD.setMessage("Starting signing in");
                    PD.setCanceledOnTouchOutside(false);
                    PD.setIndeterminate(false);
                    PD.setCancelable(true);
                    PD.show();

                    mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(task.isSuccessful()){
                                String deviceToken= FirebaseInstanceId.getInstance().getToken();
                                current_user=mAuth.getCurrentUser().getUid();
                                mDatabaseUsers.child(current_user).child("device_token").setValue(deviceToken).addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Toast.makeText(getApplicationContext(),"LOGGIN", Toast.LENGTH_SHORT).show();
                                        Intent mainIntent =new Intent(LoginActivity.this,MainActivity.class);
                                        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(mainIntent);
                                        if(PD.isShowing()){
                                            PD.dismiss();
                                        }
                                    }
                                });

                            }else{
                                Toast.makeText(getApplicationContext(),"ERROR LOGIN", Toast.LENGTH_SHORT).show();
                                if(PD.isShowing()){
                                    PD.dismiss();
                                }
                            }
                        }
                    });
                }
                else{
                    Toast.makeText(getApplicationContext(),"PLEASE ENTER THE FIELDS", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
<file_sep>package com.example.hp.firechat;

/**
 * Created by hp on 11/12/2017.
 */

public class Users {
    public String name; //this should match with the database;
    public String image;
    public String status;
    public String thumb_image;
    public Users(){

    }
    public Users(String name,String image,String status,String thumb_image){
        this.name=name;
        this.image=image;
        this.status=status;
        this.thumb_image=thumb_image;
    }
    public String getThumb_image(){
        return thumb_image;
    }
    public void setThumb_image(String thumb_image){
                this.thumb_image=thumb_image;
    }

    public String getName() {return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }
    public void setImage(String thumb_image){
        this.image=thumb_image;
    }

    public String getStatus() {
        return status;
    }
    public void setStatus(String status){
        this.status=status;
    }
}
<file_sep>package com.example.hp.firechat;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.*;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;


/**
 * A simple {@link Fragment} subclass.
 */
public class ChatsFragment extends Fragment {
    private RecyclerView mFriendsList;
    private DatabaseReference mFriendsDatabase;
    public  DatabaseReference mRootRef;
    private FirebaseAuth mAuth;
    private String mCurrentUser;
    private View mMainView;
    private DatabaseReference mUsersDatabase;
    private String name;
    private String status;
    private String image;
    private String onlineStatus;
    private Query basedOnTime;
    private int watch2,watch;
    private int numSeen;

    public ChatsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mMainView= inflater.inflate(R.layout.fragment_chats, container, false);
        mFriendsList=(RecyclerView) mMainView.findViewById(R.id.chats_list);
        mAuth=FirebaseAuth.getInstance();
        mCurrentUser=mAuth.getCurrentUser().getUid();
        mFriendsDatabase= FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrentUser);
        mRootRef=FirebaseDatabase.getInstance().getReference();
        mFriendsDatabase.keepSynced(true);
        mUsersDatabase=FirebaseDatabase.getInstance().getReference().child("Users");
        mUsersDatabase.keepSynced(true);
        mFriendsList.setHasFixedSize(true);
        mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
        mRootRef.child("seenMsgs").keepSynced(true);
       // basedOnTime=FirebaseDatabase.getInstance().getReference().child("Messages").child(mCurrentUser).orderByChild("time").startAt(System.currentTimeMillis()).endAt(System.currentTimeMillis()-86400000L);
        // Toast.makeText(getContext(),"its working bro", Toast.LENGTH_SHORT).show();

        // Inflate the layout for this fragment
        return mMainView;
    }
    @Override
    public   void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<ChatsFrag,ChatsFragment.ChatsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ChatsFrag, ChatsFragment.ChatsViewHolder>(
                ChatsFrag.class,
                R.layout.users_single_layout,
                ChatsFragment.ChatsViewHolder.class,
                mFriendsDatabase
        ) {
            @Override
            protected void populateViewHolder(final ChatsFragment.ChatsViewHolder chatsViewHolder, ChatsFrag chatsFrag, int position) {
                final String user_key = getRef(position).getKey();
               // friendsViewHolder.setDate(friends.getDate());
                mUsersDatabase.child(user_key).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        name=dataSnapshot.child("name").getValue().toString();
                        status=dataSnapshot.child("status").getValue().toString();
                        //image=dataSnapshot.child("thumb_image").getValue().toString();
                        image=dataSnapshot.child("image").getValue().toString();
                        if(dataSnapshot.hasChild("online")) {
                            onlineStatus = dataSnapshot.child("online").getValue().toString();
                            chatsViewHolder.setUserOnline(onlineStatus);
                        }

                        chatsViewHolder.setThings(getContext(),name,status,image);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

                mRootRef.child("seenMsgs").child(mCurrentUser).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        // Toast.makeText(getContext(),"coming here to check", Toast.LENGTH_SHORT).show();
                        if(dataSnapshot.hasChild(user_key)){
                            String Seen=dataSnapshot.child(user_key).child("seen").getValue().toString();
                            numSeen=Integer.parseInt(Seen);
                            // Toast.makeText(getContext(),"okay1   "+numSeen, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
                mRootRef.child("Messages").child(mCurrentUser).child(user_key).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot1) {
                        long k = dataSnapshot1.getChildrenCount();
                        // int watch=((int)k-numSeen);
                        watch2=(int)k;
                        watch=watch2-numSeen;
                        String watching=Integer.toString(watch);
                        mRootRef.child("seenMsgs").child(mCurrentUser).child(user_key).child("watch").setValue(watching).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) {
                                Log.e("success","added successfully");
                            }
                        });
                        //Toast.makeText(getContext(),"okay2   "+watch, Toast.LENGTH_SHORT).show();
                        chatsViewHolder.seenSettings(watch);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
                //  friendsViewHolder.seenSettings(user_key);
                chatsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent Chat_Intent = new Intent(getContext(), GoodChatActivity.class);
                        Chat_Intent.putExtra("Blog_id",user_key);
                        Chat_Intent.putExtra("user_name",name);
                      //  Toast.makeText(getContext(),"okay2   "+watch, Toast.LENGTH_SHORT).show();
                        String watching=Integer.toString(watch);
                        Chat_Intent.putExtra("watch",watching);
                        // StatusIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(Chat_Intent);
                    }
                });

            }

        };
        mFriendsList.setAdapter(firebaseRecyclerAdapter);
    }
    public static class ChatsViewHolder extends RecyclerView.ViewHolder{
        View mView;
        private CircleImageView mDisplayImage;
        private TextView seenNumberView;
        public TextView userStatusView;
        public ChatsViewHolder(View itemView){
            super(itemView);
            mView=itemView;
            mDisplayImage=(CircleImageView)mView.findViewById(R.id.user_single_image);
            seenNumberView=(TextView)mView.findViewById(R.id.user_single_seen);
        }
        public void setDate(String date){

        }
        public void setThings(final Context ctx, String name, String status, final String image){
            TextView userNameView=(TextView)mView.findViewById(R.id.user_single_name);
            userStatusView=(TextView)mView.findViewById(R.id.user_single_status);
          //  Toast.makeText(ctx,"it came here", Toast.LENGTH_SHORT).show();

            userStatusView.setText(status);
            userNameView.setText(name);
            if(!image.equals("default")) {
                Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mDisplayImage, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                        Picasso.with(ctx).load(image).placeholder(R.mipmap.ic_account_circle_white_48dp).into(mDisplayImage);
                    }
                });
            }

        }
        public void setUserOnline(String onlineIcon){
            ImageView userOnlineView=(ImageView)mView.findViewById(R.id.online_Icon);
            if(onlineIcon.equals("true")){
                userOnlineView.setVisibility(View.VISIBLE);
            }
            else{
                userOnlineView.setVisibility(View.INVISIBLE);
            }
        }

        public void seenSettings(int watch) {
            if(watch>0){
                String watching =Integer.toString(watch);
                seenNumberView.setText(watching);
                seenNumberView.setVisibility(View.VISIBLE);

            }
        }
    }

}
