Android chat app problem with showing live data

Viewed 50

I try to make chat app with Android, but have problem with live data. When someone of the user type message, the message doesn't display. The user need to go back and open the chat again to load the new message. I am using sql server management studio. I search for decision for the problem, but I only find answer for firebase. I need to create databaseReference and use onDataChange method. But my chat don't use firebase. And also when I send the message, I don't see it either. Do you have any idea how to make to send live data?

This is my logic

package com.example.chatappjava;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class specificchat extends AppCompatActivity {

    EditText mgetmessage;
    ImageButton msendmessagebutton;

    CardView msendmessagecardview;
    androidx.appcompat.widget.Toolbar mtoolbarofspecificchat;
    ImageView mimageviewofspecificuser;
    TextView mnameofspecificuser;

    private String enteredmessage;
    String mrecievername, recievername, recieverimage, recieverid, senderid;
    Boolean changes = false;

    ImageButton mbackbuttonofspecificchat;

    RecyclerView mmessagerecyclerview;

    Calendar calendar;
    SimpleDateFormat simpleDateFormat;

    MessagesAdapter messagesAdapter;
    ArrayList<Messages> messagesArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_specificchat);

        Intent intent = getIntent();
        senderid = intent.getStringExtra("userId");
        recieverid = intent.getStringExtra("friendId");
        recievername = intent.getStringExtra("friendName");
        recieverimage = intent.getStringExtra("friendImage");

        mgetmessage=findViewById(R.id.getmessage);
        msendmessagecardview=findViewById(R.id.carviewofsendmessage);
        msendmessagebutton=findViewById(R.id.imageviewsendmessage);
        mtoolbarofspecificchat=findViewById(R.id.toolbarofspecificchat);
        mnameofspecificuser=findViewById(R.id.Nameofspecificuser);
        mimageviewofspecificuser=findViewById(R.id.specificuserimageinimageview);
        mbackbuttonofspecificchat=findViewById(R.id.backbuttonofspecificchat);

        Picasso.get().load(recieverimage).into(mimageviewofspecificuser);
        mnameofspecificuser.setText(recievername);


        messagesArrayList=new ArrayList<>();
        mmessagerecyclerview=findViewById(R.id.recyclerviewofspecific);

        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);
        mmessagerecyclerview.setLayoutManager(linearLayoutManager);
        messagesAdapter=new MessagesAdapter(specificchat.this,messagesArrayList, Integer.parseInt(senderid));
        mmessagerecyclerview.setAdapter(messagesAdapter);

        setSupportActionBar(mtoolbarofspecificchat);

        calendar=Calendar.getInstance();
        simpleDateFormat=new SimpleDateFormat("hh:mm a");

        messagesArrayList.clear();
        try {
            Connection conn = DatabaseConnection.createDatabaseConnection();
            Statement statement = conn.createStatement();

            ResultSet resultat = statement.executeQuery("select SENDER_ID, RECIEVER_ID ,MESSAGE, SHORT_TIME, FULL_TIME from MESSAGES where (SENDER_ID = " +  senderid + " and RECIEVER_ID = " +  recieverid + ") or (SENDER_ID = " +  recieverid + " and RECIEVER_ID = " +  senderid + ") order by FULL_TIME");
            while (resultat.next()) {
                messagesArrayList.add(new Messages(resultat.getString("MESSAGE"), resultat.getString("SENDER_ID"), resultat.getString("RECIEVER_ID"), resultat.getString("SHORT_TIME"), resultat.getString("FULL_TIME")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        messagesAdapter=new MessagesAdapter(specificchat.this,messagesArrayList,Integer.parseInt(senderid));
        messagesAdapter.notifyDataSetChanged();



        mbackbuttonofspecificchat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });



        msendmessagebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                enteredmessage=mgetmessage.getText().toString();
                if(enteredmessage.isEmpty()) {
                    Toast.makeText(getApplicationContext(),"Enter message first",Toast.LENGTH_SHORT).show();
                } else {
                    Calendar c = Calendar.getInstance();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String strDate = sdf.format(c.getTime());
                    Messages messages = new Messages(enteredmessage, senderid, recieverid, strDate.substring(11,16), strDate);
                    try {
                        Connection conn = DatabaseConnection.createDatabaseConnection();

                        String sql = "INSERT INTO MESSAGES" +
                                "(SENDER_ID, RECIEVER_ID, MESSAGE, SHORT_TIME, FULL_TIME) " +
                                "VALUES (?, ?, ?, ?, ?)";
                        PreparedStatement pstmt = conn.prepareStatement(sql);
                        pstmt.setString(1, messages.getSenderId());
                        pstmt.setString(2, messages.getRecieverId());
                        pstmt.setString(3, messages.getMessage());
                        pstmt.setString(4, messages.getShortTime());
                        pstmt.setString(5, messages.getLongTime());

                        int result = pstmt.executeUpdate();
                        messagesArrayList.add(messages);
                        messagesAdapter.notifyDataSetChanged();
                        if (result != 0) {
                            mgetmessage.setText(null);
                            changes = true;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    @Override
    public void onStart() {
        super.onStart();
        messagesAdapter.notifyDataSetChanged();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (messagesAdapter!=null) {
            messagesAdapter.notifyDataSetChanged();
        }
    }
}

This is my adapter

package com.example.chatappjava;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

 class MessagesAdapter extends RecyclerView.Adapter {

    Context context;
    ArrayList<Messages> messagesArrayList;
    int senderId;

    int ITEM_SEND=1;
    int ITEM_RECIEVE=2;

    public MessagesAdapter(Context context, ArrayList<Messages> messagesArrayList, int senderId) {
        this.context = context;
        this.messagesArrayList = messagesArrayList;
        this.senderId = senderId;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if(viewType==ITEM_SEND)
        {
            View view= LayoutInflater.from(context).inflate(R.layout.senderchatlayout,parent,false);
            return new SenderViewHolder(view);
        }
        else
        {
            View view= LayoutInflater.from(context).inflate(R.layout.recieverchatlayout,parent,false);
            return new RecieverViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        Messages messages=messagesArrayList.get(position);
        if(holder.getClass()==SenderViewHolder.class)
        {
            SenderViewHolder viewHolder=(SenderViewHolder)holder;
            viewHolder.textViewmessaage.setText(messages.getMessage());
            viewHolder.timeofmessage.setText(messages.getShortTime());
        }
        else
        {
            RecieverViewHolder viewHolder=(RecieverViewHolder)holder;
            viewHolder.textViewmessaage.setText(messages.getMessage());
            viewHolder.timeofmessage.setText(messages.getShortTime());
        }
    }


    @Override
    public int getItemViewType(int position) {
        Messages messages=messagesArrayList.get(position);
        if(senderId == Integer.parseInt(messages.getSenderId()))
        {
          return  ITEM_SEND;
        }
        else
        {
            return ITEM_RECIEVE;
        }
    }

    @Override
    public int getItemCount() {
        return messagesArrayList.size();
    }

    class SenderViewHolder extends RecyclerView.ViewHolder
    {

        TextView textViewmessaage;
        TextView timeofmessage;


        public SenderViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewmessaage=itemView.findViewById(R.id.sendermessage);
            timeofmessage=itemView.findViewById(R.id.timeofmessage);
        }
    }

    class RecieverViewHolder extends RecyclerView.ViewHolder
    {

        TextView textViewmessaage;
        TextView timeofmessage;


        public RecieverViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewmessaage=itemView.findViewById(R.id.sendermessage);
            timeofmessage=itemView.findViewById(R.id.timeofmessage);
        }
    }




}

And this is my layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_height="match_parent"
    android:background="#ECE5DD"
    tools:context=".specificchat">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_marginTop="0dp"
        android:background="@color/dark_blue"
        android:id="@+id/toolbarofspecificchat">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical">


            <ImageButton
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:id="@+id/backbuttonofspecificchat"
                android:tint="@color/white"
                android:src="@drawable/ic_baseline_arrow_back_24"
                android:background="@android:color/transparent"
                android:layout_centerVertical="true"/>

            <androidx.cardview.widget.CardView
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:id="@+id/cardviewfospecificchat"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@id/backbuttonofspecificchat"
                android:layout_centerVertical="true"
                app:cardCornerRadius="35dp">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@drawable/defaultimage"
                    android:id="@+id/specificuserimageinimageview"
                    android:scaleType="centerCrop"/>

            </androidx.cardview.widget.CardView>


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/nameOfUser"
                android:textSize="20sp"
                android:layout_toRightOf="@+id/cardviewfospecificchat"
                android:id="@+id/Nameofspecificuser"
                android:layout_marginLeft="10dp"
                android:layout_centerVertical="true"
                android:textStyle="bold"
                android:textColor="@color/white"/>
        </RelativeLayout>




    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/getmessage"
        android:id="@+id/recyclerviewofspecific"
        android:layout_below="@id/toolbarofspecificchat"
        android:padding="5dp">

    </androidx.recyclerview.widget.RecyclerView>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="@string/TypeMessage"
        android:layout_marginLeft="5dp"
        android:layout_marginBottom="5dp"
        android:paddingLeft="20dp"
        android:paddingEnd="10dp"
        android:textSize="18sp"
        android:background="@drawable/messagebackgroun"
        android:textAlignment="textStart"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="55dp"
        android:textColor="@color/black"
        android:textColorHint="#A8A7A7"
        android:id="@+id/getmessage" />


    <androidx.cardview.widget.CardView
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:id="@+id/carviewofsendmessage"
        android:layout_toRightOf="@id/getmessage"
        android:layout_marginLeft="-50dp"
        android:layout_marginBottom="5dp"
        android:backgroundTint="@color/dark_blue"
        android:layout_alignParentBottom="true"
        app:cardCornerRadius="45dp">


        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_baseline_arrow_forward_24"
            android:padding="5dp"
            android:backgroundTint="@android:color/transparent"
            android:background="@android:color/transparent"
            android:id="@+id/imageviewsendmessage"
            android:layout_gravity="center"
            android:scaleType="centerCrop"
            app:tint="@color/white">

        </ImageButton>



    </androidx.cardview.widget.CardView>

</RelativeLayout>
0 Answers
Related