How to delete an entry from a RecyclerView in realtime - java

I am trying to create a chat. However, I am facing a big issue. When I delete an entry from the chat recyclerView, the entry stays there, but is removed from the firebase db as expected (I mean only removing from db is working). It only disapears when I close the activity and open it again. My recyclerView has a feature of load 10 more entries each time a user scrolls.
I dont understand how can I remove the entry from the recyclerView?
I need to call the function loadMoreMessages()? Refresh the activity?
MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
public class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView messageText, displayName;
public CircleImageView profileImage;
public ImageView messageImage;
public MessageViewHolder(View itemView) {
super(itemView);
messageText = (TextView) itemView.findViewById(R.id.message_text_layout);
profileImage = (CircleImageView) itemView.findViewById(R.id.message_profile_layout);
displayName = (TextView) itemView.findViewById(R.id.name_text_layout);
messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
}
}
private List<Messages> mMessageList;
private FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
private DatabaseReference mUserDatabaseSettings;
private String rul, fromUser_t;
private UserAccountSettings mUserAccountSettings;
public MessageAdapter(List<Messages> mMessageList) {
this.mMessageList = mMessageList;
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_single_layout,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(final MessageViewHolder holder, final int position) {
final String current_user_id = mAuth.getCurrentUser().getUid();
final Messages c = mMessageList.get(position);
final String from_user = c.getFrom();
final String message_type = c.getType();
final String messageContent = c.getMessage();
/**
* popup for text message
*/
// check if the message is from the current user
if(from_user.equals(current_user_id))
{
holder.messageText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//popup menu to select option
CharSequence options[] = new CharSequence[]
{
"Delete from my phone",
"Delete for Everyone" ,
"Cancel"
};
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle("Message Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0)
{
deleteSentMessage(position, holder);
// Intent intent = new Intent(holder.itemView.getContext(), ChatActivity.class);
// holder.itemView.getContext().startActivity(intent);
//MessageViewHolder.class.notify();
holder.messageText.setPaintFlags(holder.messageText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else if(i == 1)
{
deleteMessageForEveryOne(position, holder);
// Intent intent = new Intent(holder.itemView.getContext(), ChatActivity.class);
// holder.itemView.getContext().startActivity(intent);
//notifyDataSetChanged();
//holder.messageText.setVisibility(View.GONE);
}
}
});
builder.show();
}
});
}else
{
// similar code to check if the message is from the other user
}
holder.messageText.setVisibility(View.GONE);
holder.messageImage.setVisibility(View.GONE);
if("text".equals(message_type))
{
holder.messageText.setVisibility(View.VISIBLE);
if(from_user.equals(current_user_id))
{
holder.messageText.setBackgroundResource(R.drawable.message_text_background);
holder.messageText.setTextColor(Color.WHITE);
//todo left right not working
holder.messageText.setGravity(Gravity.LEFT);
}else
{
holder.messageText.setBackgroundColor(Color.WHITE);
holder.messageText.setTextColor(Color.BLACK);
holder.messageText.setGravity(Gravity.RIGHT);
}
holder.messageText.setText(c.getMessage());
}else
{
holder.messageImage.setVisibility(View.VISIBLE);
UniversalImageLoader.setImage(messageContent,holder.messageImage,null,"");
}
}
#Override
public int getItemCount() {
return mMessageList.size();
}
/**
function to Delete from my phone
**/
private void deleteSentMessage(final int position, final MessageViewHolder holder)
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("messages")
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(holder.itemView.getContext(), "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(holder.itemView.getContext(), "Error Occurred.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
function to Delete from receiver phone
**/
private void deleteReceiveMessage(final int position, final MessageViewHolder holder)
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("messages")
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(holder.itemView.getContext(), "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(holder.itemView.getContext(), "Error Occurred.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
function to Delete from both sides
**/
private void deleteMessageForEveryOne(final int position, final MessageViewHolder holder)
{
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("messages")
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
rootRef.child("messages")
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(holder.itemView.getContext(), "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
}
});
}else
{
Toast.makeText(holder.itemView.getContext(), "Error Occurred.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
ChatActivity.java
public class ChatActivity extends AppCompatActivity {
private static final String TAG = "ChatActivity";
//todo check is user is logedin
//user with whom Iam talking to
private String mChatUser;
private Toolbar mChatToolbar;
private DatabaseReference mRootRef;
private TextView mTitleView, mLastSeenView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private ImageButton mChatAddBtn;
private ImageButton mChatSendBtn;
private EditText mChatMessageView;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout;
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager mLinearLayout;
private MessageAdapter mAdapter;
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private int itemPos =0;
private String mLastKey = "";
private String mPrevKey = "";
private static final int GALLERY_PICK = 1;
//Storage Firebase
private StorageReference mImageStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// create a toolbar and set the title as the user with we are chatting to
mChatToolbar = (Toolbar) findViewById(R.id.chat_app_bar);
setSupportActionBar(mChatToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// to add a custom view to the toolbar
actionBar.setDisplayShowCustomEnabled(true);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mChatUser = getIntent().getStringExtra("user_id");
String userName = getIntent().getStringExtra("user_name");
getSupportActionBar().setTitle(userName);
// String userName = getIntent().getStringExtra("user_name");
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);
// ---------- Custom Action bar items ---
mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mLastSeenView = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_btn);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mAdapter = new MessageAdapter(messagesList);
mImageStorage= FirebaseStorage.getInstance().getReference();
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
//mMessagesList.setItemViewCacheSize(25);
mMessagesList.setDrawingCacheEnabled(true);
mMessagesList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mMessagesList.setAdapter(mAdapter);
loadMessages();
mTitleView.setText(userName);
mRootRef.child("users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("lastSeen").getValue().toString();
//String image = dataSnapshot.child()
if(online.equals("true")){
mLastSeenView.setText("Online");
}else {
GetTimeAgo getTimeAgo = new GetTimeAgo();
long lastTime = Long.parseLong(online);
String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
mLastSeenView.setText(lastSeenTime);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen", false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Chat/" + mCurrentUserId + "/" + mChatUser, chatAddMap); //add map to current user
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
if(databaseError != null){
//Log.d(TAG, "onComplete: CHAT LOG", databaseError.getMessage());
Log.e(TAG, "onComplete: CHAT_LOG" + databaseError.getMessage().toString());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
// open gallery to get an image
mChatAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,"SELECT IMAGE"), GALLERY_PICK);
}
});
//pagination
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
// each time it loads a new page should go to position zero
itemPos = 0;
loadMoreMessages();
}
});
}
/**
* load more messages everytime uesr refreshes
*/
private void loadMoreMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if(!mPrevKey.equals(messageKey)){
messagesList.add(itemPos++, message);
Log.d(TAG, "onChildAdded: xx" + mPrevKey + "---" + mLastKey);
} else {
mPrevKey = mLastKey;
}
if(itemPos == 1){
mLastKey = messageKey;
}
Log.d(TAG, "onChildAdded: TOTALKEUS" + "lastkey: " + mLastKey + " | Prev key : " + mPrevKey + " | Message Key : " + messageKey);
mAdapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
mLinearLayout.scrollToPositionWithOffset(itemPos , 0);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
/**
* method used to load messages once
*/
private void loadMessages() {
//query to get pagination and last 10 messages
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages message = dataSnapshot.getValue(Messages.class);
itemPos++;
if(itemPos == 1){
// get the key to be user as a start point when loading more items
String messageKey = dataSnapshot.getKey();
mLastKey = messageKey;
mPrevKey = messageKey;
Log.d(TAG, "onChildAdded: last " +mLastKey + " prev " + mPrevKey + " messa " + messageKey + "-----------");
}
messagesList.add(message);
mAdapter.notifyDataSetChanged();
//pagination - define the bottom of the recycler view
//automatic scroll to bottom
mMessagesList.scrollToPosition(messagesList.size() - 1);
mRefreshLayout.setRefreshing(false);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
/**
* send photo message
* #param requestCode
* #param resultCode
* #param data
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
final String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();
final String push_id = user_message_push.getKey();
StorageReference filepath = mImageStorage.child("message_images").child( push_id + ".jpg");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String download_url = uri.toString();
Map messageMap = new HashMap();
messageMap.put("message", download_url);
messageMap.put("seen", false);
messageMap.put("type", "image");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from", mCurrentUserId);
messageMap.put("to", mChatUser);
messageMap.put("messageID", push_id );
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.setText("");
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
});
}
}
});
}
}
}
``

You're using a ChildEventListener in your messageQuery, which has these main methods:
onChildAdded, which is called initially for every child node matching your messageQuery query, and subsequently when any child node is added to the database that falls into messageQuery.
onChildRemoved, which is called when any child node (that falls) is removed from the database (or at least to the part that messageQuery is listening to).
onChildChanged, which is called when any child node that messageQuery is listening is modified in the database.
If I look at your implementation, you've only implemented onChildAdded. So when you remove a child node from the database, Firebase tells your ChildEventListener about it, but that then does nothing.
To remove the message from the UI when it gets removed from the database, you will need to implement:
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
// TODO: remove the message matching dataSnapshot from messagesList
// TODO: call adapter.notifyDataSetChanged() so that the UI gets updates
}

The list changes size so you have to give new list size to your logic.

Thanks Frank and Vedprakash. It was a quit obvious. At that time I did not understand how to pass the position and remove the item using onChildRemoved. Now I understand. What I did was based on this post: How to use onChildRemoved in Firebase Realtime Database?
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Toast.makeText(ChatActivity.this, "Entered on this part!", Toast.LENGTH_SHORT).show();
int index = keyList.indexOf(dataSnapshot.getKey());
messagesList.remove(index);
keyList.remove(index);
//mAdapter.notifyDataSetChanged();
mAdapter.notifyItemRemoved(index);
}
I tested it and is working fine. However, It has a little issue. My chat loads 10 items (defined by: private static final int TOTAL_ITEMS_TO_LOAD = 10;). If the user scrolls it will load more items.
When I open the chat page, the items loaded are from "2" to "11" But, when I delete item, for example, "9" the item "1" show up. Meaning that, the item right before the position zero of the messagesList will show up.
I tried several things. My last try was set the mLinearLayout.scrollToPosition, decrease the TOTAL_ITEMS_TO_LOAD. And the issue stays alive. :(
Before delete
After delete item

Related

Messages duplicates twice when a user sends a message [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm building a chat application that sends messages and media files, my problem is that when a user sends a message or a media file it displays twice. But when I close my chat activity and open it again it displays as expected i.e. once.
My Chat Activity
public class ChatActivityy extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
messageSenderID = mAuth.getCurrentUser().getUid();
Rootref = FirebaseDatabase.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference("Users");
messageReceiverID = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("visit_user_name").toString();
//Toast.makeText(this, messageReceiverID, Toast.LENGTH_SHORT).show();
//Toast.makeText(this, messageReceiverName, Toast.LENGTH_SHORT).show();
InitializeControllers();
DisplayLastSeen();
GetUserInfo();
userName.setText(messageReceiverName);
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notify = true;
SendMessage();
//MessageInputText.setText("");
}
});
SendFilesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence[] options = new CharSequence[]
{
"Images",
"Videos",
"Documents",
"Audio",
"Cancel"
};
AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivityy.this);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
}
});
builder.show();
}
});
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null & data.getData() !=null)
{
loadingBar.setTitle("Sending file");
loadingBar.setMessage("Please wait, your file is sending");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
fileUri = data.getData();
if(checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files");
String messageSenderRef = "Messages/" + messageSenderID + "/" + messageReceiverID;
String messageReceiverRef = "Messages/" + messageReceiverID + "/" + messageSenderID;
DatabaseReference userMessageKeyRef = Rootref.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID = userMessageKeyRef.getKey();
final StorageReference filepath = storageReference.child(messagePushID + "." + "jpg");
uploadTask = filepath.putFile(fileUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful())
{
throw task.getException();
}
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful())
{
Uri downloadUrl = task.getResult();
myUrl = downloadUrl.toString();
Map messageTextBody = new HashMap();
messageTextBody.put("message", myUrl);
messageTextBody.put("name", fileUri.getLastPathSegment());
messageTextBody.put("type", checker);
messageTextBody.put("from", messageSenderID);
messageTextBody.put("to", messageReceiverID);
messageTextBody.put("messageID", messagePushID);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef + "/" + messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushID, messageTextBody);
Rootref.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
// Toast.makeText(ChatActivityy.this, "Message Sent", Toast.LENGTH_SHORT).show();
} else {
loadingBar.dismiss();
Toast.makeText(ChatActivityy.this, "Message not sent", Toast.LENGTH_SHORT).show();
}
MessageInputText.setText("");
}
});
}
}
});
}
else
{
loadingBar.dismiss();
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onStart() {
super.onStart();
Rootref.child("Messages").child(messageSenderID).child(messageReceiverID)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendMessage()
{
String messageText = MessageInputText.getText().toString();
if (TextUtils.isEmpty(messageText))
{
Toast.makeText(this, "Enter a Message", Toast.LENGTH_SHORT).show();
}
else {
String messageSenderRef = "Messages/" + messageSenderID + "/" + messageReceiverID;
String messageReceiverRef = "Messages/" + messageReceiverID + "/" + messageSenderID;
DatabaseReference userMessageKeyRef = Rootref.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
String messagePushID = userMessageKeyRef.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message", messageText);
messageTextBody.put("type", "text");
messageTextBody.put("from", messageSenderID);
messageTextBody.put("to", messageReceiverID);
messageTextBody.put("messageID", messagePushID);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef + "/" + messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushID, messageTextBody);
Rootref.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
// Toast.makeText(ChatActivityy.this, "Message Sent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ChatActivityy.this, "Message not sent", Toast.LENGTH_SHORT).show();
}
MessageInputText.setText("");
}
});
final String msg = messageText;
// UsersRef.child(messageSenderID);
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Friends user = dataSnapshot.getValue(Friends.class);
if (notify) {
sendNotification(messageReceiverID, user.getName(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My Adapter
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>
{
private List<Messages> userMessagesList;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
MessageAdapter(List<Messages> userMessagesList) {
this.userMessagesList = userMessagesList;
}
class MessageViewHolder extends RecyclerView.ViewHolder
{
TextView senderMessageText, receiverMessageText;
ZoomageView senderImage, receiverImage;
ImageView senderMedia, receiverMedia;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
senderMessageText = (TextView) itemView.findViewById(R.id.sender_message_text);
receiverMessageText = (TextView) itemView.findViewById(R.id.receiver_message_text);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_messages_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder messageViewHolder, final int position) {
String messageSenderID = mAuth.getCurrentUser().getUid();
final Messages messages = userMessagesList.get(position);
String fromUserID = messages.getFrom();
String fromMessageType = messages.getType();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
messageViewHolder.receiverMessageText.setVisibility(View.GONE);
messageViewHolder.senderMessageText.setVisibility(View.GONE);
if (fromMessageType.equals("text")) {
if (fromUserID.equals(messageSenderID)) {
messageViewHolder.senderMessageText.setVisibility(View.VISIBLE);
messageViewHolder.senderMessageText.setBackgroundResource(R.drawable.sender_message);
messageViewHolder.senderMessageText.setTextColor(Color.BLACK);
messageViewHolder.senderMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
} else {
messageViewHolder.receiverMessageText.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setBackgroundResource(R.drawable.receiver_messages_layout);
messageViewHolder.receiverMessageText.setTextColor(Color.BLACK);
messageViewHolder.receiverMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
}
}
if (fromUserID.equals(messageSenderID))
{
messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userMessagesList.get(position).getType().equals("text"))
{
CharSequence[] options = new CharSequence[]
{
"Delete for me",
"Delete for Everyone",
"Copy",
"Cancel"
};
AlertDialog.Builder builder = new AlertDialog.Builder(messageViewHolder.itemView.getContext());
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0)
{
deleteSentMessage(position, messageViewHolder);
}
else if (i == 1)
{
deleteMessageForEveryone(position, messageViewHolder);
}
else if (i == 2)
{
ClipboardManager myClipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData myClip = ClipData.newPlainText("label", messageViewHolder.senderMessageText.getText().toString());
myClipboard.setPrimaryClip(myClip);
Toast.makeText(v.getContext(), "Copied to clipboard" , Toast.LENGTH_SHORT ).show();
//setClipboard(mContext, messageViewHolder.senderMessageText.toString());
}
}
});
builder.show();
}
}
#Override
public int getItemCount() {
return userMessagesList.size();
}
}
This might be because you attach a listener in onStart. After you start a new intent, the activity is paused, and then, after the user has added a new message and resumed the old activity, method onStart is called one more time. So at that moment you have two listeners. If the next added message is duplicated three times, then it must be the actual problem. Try moving EventListener to onCreate. Or check if it is already assigned to your directory (Idk if this is possible with the database), if you want to leave it in onStart

read a realtime database node

hi guys I would like as a title to read a single node created previously in my realtime firebase database, the database is thus created:
Users
---- UID1
---- Email:
---- Fullname:
---- Phone:
---- Coins:
---- UID2
---- Email:
---- Fullname:
---- Phone:
---- Coins:
so my database has a structure like the one shown and I need to read in onDataChange and then write the data in a TextView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this method I used doesn't work as I can't get it to take the data I need.
I need to take the Coins value: within each different logged user, so each logged in user reads his data.
I the UID value that identifies each user, I created it based on his mobile number, so each user has his own mobile number that identifies him as UID.
this is all my code, as you can see the data that saves the UID is contained in mPhone, which was saved and then brought into this activity through the SharedPreferences.
public class PageCoins_Activity extends AppCompatActivity implements RewardedVideoAdListener {
private static final String TAG = MainActivity.class.getName();
private FirebaseAuth mAuth;
private AdView mBannerTop;
private AdView mBannerBot;
private RewardedVideoAd mRewardedVideoAd;
public double Coins;
double coinsOp = 0.00;
double coinsCl = 0.00;
double coinssum = 0.00;
Button mButton;
Button mPhonebtn;
TextView mCoinscounter;
TextView mCoins;
FirebaseDatabase mDatabase;
EditText mPhoneEdt;
TextView mPhone;
#Override
protected void onStart(){
super.onStart();
updateUI();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mAuth = FirebaseAuth.getInstance();
initFirebase();
//counter CRD
mCoinscounter = (TextView)findViewById(R.id.Textcoins);
mButton = (Button)findViewById(R.id.btn2);
mPhoneEdt = (EditText)findViewById(R.id.NumberPhEdt);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mCoins = (TextView)findViewById(R.id.txtGen);
mPhonebtn = (Button)findViewById(R.id.buttonPhone);
//mPhoneEdt.setVisibility(View.GONE);
//mPhone.setVisibility(View.VISIBLE);
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins Day %").setValue(mCoinscounter.getText().toString());
}
});
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Banner Top View Coins
mBannerTop = (AdView) findViewById(R.id.adViewTopcoins);
AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerTop.loadAd(adRequest);
// Banner Bot View Coins
mBannerBot = (AdView) findViewById(R.id.adViewBotcoins);
AdRequest adRequest1 = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerBot.loadAd(adRequest1);
getnumberprefs();
//ADMob Video
loadRewardedVideoAd();
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register_Activity.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register_Activity.KEY_NUMB,null);
mPhone.setText(numberphn);
}
//boolean changepgcoins = true;
public void changeNumber(View view) {
/*if (changepgcoins == true){
mPhoneEdt.setVisibility(View.GONE);
mPhone.setVisibility(View.VISIBLE);
changepgcoins = false;
}else{
mPhoneEdt.setVisibility(View.VISIBLE);
mPhone.setVisibility(View.GONE);
changepgcoins = true;
}*/
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
public void HomeClick(View view){
Intent intenthome = new Intent(this, MainActivity.class);
finish();
startActivity(intenthome);
}
public void displayCrd (double amount){
mCoinscounter.setText(String.format("%.2f", amount));
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
public void logout(View view) {
mAuth.signOut();
updateUI();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, Login_Activity.class);
finish();
startActivity(intTologin);
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d(TAG, "Video Caricato");
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, " RAPp " + " COINS " + " : " + rewardItem.getAmount(), Toast.LENGTH_LONG).show();
Coins += rewardItem.getAmount();
displayCrd(Coins/40200*100);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.d(TAG, "Caricamento Fallito");
}
#Override
public void onRewardedVideoCompleted() {
loadRewardedVideoAd();
}
#Override
protected void onDestroy() {
if (!isEmpty(mCoins)){
String coinsopen = mCoins.getText().toString();
String coinscounter = mCoinscounter.getText().toString();
coinsOp = Double.parseDouble(String.format(coinsopen.replace(',', '.'), "%.2f"));
coinsCl = Double.parseDouble(String.format(coinscounter.replace(',', '.'), "%.2f"));
coinssum = (coinsOp + coinsCl);
mCoinscounter.setText(String.valueOf(coinssum));
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}else{
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}
super.onDestroy();
}
private boolean isEmpty(TextView mCoins) {
String input = mCoins.getText().toString();
return input.length() == 0.00;
}
}
I really ask for help on the solution of this thing because it's the last thing I need to finish and I can't thank you.
{
"Utenti" : {
"3********4" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
"3********1" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
}
}
this is my database so composed.

Check if is user first login on Android App using Firebase Auth and Database

I am making an chat app and I want to do the following:
When starting the MainActivity, check if the user is logged in. If not, start FirebaseAuthUI.
But FirebaseAuth only supports a few parameters and, to add more, I created a Database node do each user, which store other parameters.
To get this parameters, after finishing FirebaseAuth, the user is redirected to an Activity that get all extra information and store in the user's node in the Database. All of this is working just fine.
But after the user fill the information in this Info Activity and finish the register, it should go back to MainActivity and stay there. How can I do that?
I am trying it this way:
I added to each user a Boolean variable called userCompleted, which informs if the user have already gave their information. I check if this variable is false, and if so, I call the Info Activity intent and, in the when the user press the button to complete the registration in this Activity, it sets the userCompleted value to true in the user node in the Database and then start an intent that leads to MainActivity.
The problem is that in the Database, userCompleted is set to true and then immediately goes back to false, and I don't know why. Also, I guess I am having trouble on reading userCompleted from the Database, probably because I haven't worked much with asynchronous tasks.
I used a variable isUserCompleted declared in Main Activity to get track of the userCompleted value.
A way to check if is the first time the user is logging in would be useful too, although it wouldn't solve my whole problem.
This is my current code:
(if need more to try to understand the problem just ask in the comments)
Create AuthStateListener
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
onSignInInitialize(user);
Log.d(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
onSignInInitialize()
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.d(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.d(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.d(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
Go back to Main Activity
mFinishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mUserDatabaseReference.child("userCompleted").setValue(true);
Intent intent = new Intent (CreateVolunteerProfile.this, SearchActivity.class);
startActivity(intent);
}
});
Entire MainActivity block (Actually it's called SearchActivity)
public class SearchActivity extends AppCompatActivity implements RecyclerAdapter.UserItemClickListener {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<User> users = new ArrayList<User>();
private String mLoggedUserId = "user2";
private String mLoggedUsername;
private User mLoggedUser;
private FirebaseUser mLoggedFBUser;
//private boolean isUserCompleted;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
private boolean firstTime = true;
private static final String TAG = "Search Activity";
private static final int USER_CLICK = 1;
private static final int RC_SIGN_IN = 1;
private static final int RC_CREATE_PROFILE = 2;
//Firebase
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mUsersDatabaseReference;
private DatabaseReference mUserReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
View loadingView = findViewById(R.id.cl_loading);
loadingView.setVisibility(View.VISIBLE);
//RecyclerView
recyclerView = findViewById(R.id.rv_users);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(users, this);
recyclerView.setAdapter(adapter);
//Firebase
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
setAuthStateListener();
loadingView.setVisibility(View.GONE);
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null)
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
detachChildEventListener();
clearAdapter();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.wtf(TAG, "onSaveInstanceState userId = "+ mLoggedUserId);
//Log.wtf(TAG, "UserCompleted (onSaveInstanceState) " + isUserCompleted);
outState.putString("userId", mLoggedUserId);
//outState.putBoolean("isUserCompleted", isUserCompleted);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mLoggedUserId = savedInstanceState.getString("userId");
//isUserCompleted = savedInstanceState.getBoolean("isUserCompleted");
//Log.wtf(TAG, "UserCompleted (onRestoreInstanceState) " + isUserCompleted);
Log.wtf(TAG, "onRestoreInstanceState userId = "+ mLoggedUserId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if((requestCode == RC_SIGN_IN) && firstTime){
if (resultCode == RESULT_OK){
//Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(this, "Sign in canceled!", Toast.LENGTH_SHORT).show();
finish();
}
}
if((requestCode == RC_CREATE_PROFILE)){
if (resultCode == RESULT_OK){
//isUserCompleted = true;
}
}
}
#Override
public void onUserItemClick(int clickedUserIndex) {
Intent intent = new Intent (this, ChatActivity.class);
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if(user != null) {
mLoggedUserId = user.getUid();
intent.putExtra("user1", mLoggedUserId);
String mUserRecieverId = users.get(clickedUserIndex).getUid();
intent.putExtra("user2", mUserRecieverId);
Log.wtf(TAG, "SearchActivity // user = " + users.get(clickedUserIndex));
Log.wtf("1", "SearchActivity // mLoggedUserId = " + mLoggedUserId + " // users.getUid() = " + users.get(clickedUserIndex).getUid());
startActivityForResult(intent, USER_CLICK);
}
else {
Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
}
}
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
mUserReference = mUsersDatabaseReference.child(user.getUid());
onSignInInitialize(user);
Log.wtf(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
boolean isUserCompleted = false;
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.wtf(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.wtf(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.wtf(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
public void onSignOutCleanup(){
mLoggedUser = null;
mLoggedUserId = null;
mLoggedUsername = null;
detachChildEventListener();
clearAdapter();
}
public void attachChildEventListener(){
if (mChildEventListener == null){
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User user = dataSnapshot.getValue(User.class);
users.add(user);
Log.d(TAG, "onChildAdded userId = "+ user.getUid());
//adapter.notifyItemInserted(users.size()-1);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) { }
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) { }
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) { }
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
};
}
mUsersDatabaseReference.addChildEventListener(mChildEventListener);
}
public void detachChildEventListener(){
if (mChildEventListener != null){
mUsersDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
public void clearAdapter() {
final int size = users.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
users.remove(0);
}
adapter.notifyItemRangeRemoved(0, size);
}
}
public void startCreateProfileActivity(FirebaseUser user){
mUsersDatabaseReference.child(user.getUid()).child("userCompleted").setValue(false);
Intent intent = new Intent(SearchActivity.this, CreateProfileActivity.class);
intent.putExtra("userId", user.getUid());
startActivityForResult(intent, RC_CREATE_PROFILE);
}
public void startLoginUI(){
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setLogo(R.mipmap.logo)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.GoogleBuilder().build(),
//new AuthUI.IdpConfig.FacebookBuilder().build(),
//new AuthUI.IdpConfig.TwitterBuilder().build(),
//new AuthUI.IdpConfig.GitHubBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build()))
//new AuthUI.IdpConfig.PhoneBuilder().build(),
//new AuthUI.IdpConfig.AnonymousBuilder().build()))
.build(),
RC_SIGN_IN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_item:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I think the simplest way is if a user clicked on finish Btn successfully make a flag with true else make it false
in your MainActivity
firebase.auth().onAuthStateChanged(function(user) {
// User signed in and not registered
if (user&&!isPressedOnFinishBtn) {
// User is signed in.
}
user clicked on finish btn
else if(isPressedOnFinishBtn) {
// No user is signed in.
}
});
This is how you can do that .
Create a method inside your Login activity .
private void AllowUserToLogin() {
String userName = userEmail.getText().toString();
String userPass = userPassword.getText().toString();
if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) {
Toast.makeText(this, "Enter user Name / password first . . .", Toast.LENGTH_SHORT).show();
} else {
dialogBar.setTitle("Sign In ");
dialogBar.setMessage("Please Wait . . .");
dialogBar.setCanceledOnTouchOutside(true);
dialogBar.show();
mAuth.signInWithEmailAndPassword(userName, userPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String currentUserID = mAuth.getCurrentUser().getUid();
String deviceToken = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
UsersRef.child(currentUserID).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserToMainActivity();
Toast.makeText(LoginPage.this, "Logged in Successfull . . . ", Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
} else {
String error = task.getException().toString();
Toast.makeText(LoginPage.this, "Wrong Email or Password: " + error, Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
}
}
and on ur onClick() method .
#Override
public void onClick(View v) {
if (v == needNewAccount) {
sendUserToRegisterActivity();
} else if (v == loginButton) {
AllowUserToLogin();
}else if(v == phone_button){
Intent phoneLoginIntent = new Intent(LoginPage.this , PhoneLoginActivity.class);
startActivity(phoneLoginIntent);
}
}
this is sendUserToRegisterActivity()
private void sendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginPage.this, RegisterationForm.class);
startActivity(registerIntent);
}
This is sendUserToMainActivity() .
private void sendUserToMainActivity() {
Intent mainIntent = new Intent(LoginPage.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}

AppWidget is frozen before message has been sent or recieved. How to initiate the intent before messages are sent?

So appwidget is fixed after some help on here but before any message has been sent or received the intent to launch the ChatRoomActivity doesn't work.
How could I set it up so it's intent launches the activity before any message has been sent/received(obviously it would have no message but it has a textView saying click to open chat..etc).
my code:
public class ProTalkWidget extends AppWidgetProvider {
private static final String ACTION_BROADCASTWIIDGET = "ACTION_BROADCASTWIIDGET";
public static final String PROTALK_APPWIDGET_UPDATE = "PROTALK_APPWIDGET_UPDATE";
private final int REQUEST_CODE = 0;
public static final String USER_ID = "userId";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String msgReceiverId;
private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
final int appWidgetId) {
//Construct the RemoteViews object
final RemoteViews views;
views = new RemoteViews(context.getPackageName(), R.layout.pro_talk_widget);
Intent intent = new Intent(context, ProTalkWidget.class);
intent.setAction(ACTION_BROADCASTWIIDGET);
context.sendBroadcast(intent);
appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(PROTALK_APPWIDGET_UPDATE.equals(intent.getAction())){
Log.i("onReceive", "getting onReceived!");
handleMsg(intent, context);
}
}
private void handleMsg(final Intent intent, final Context ctx){
msgReceiverId = intent.getStringExtra("receiverId");
if(msgReceiverId!=null) {
String my_Id = mAuth.getCurrentUser().getUid();
final RemoteViews views;
views = new RemoteViews(ctx.getPackageName(), R.layout.pro_talk_widget);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Messages").child(my_Id).child(msgReceiverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Messages messages = ds.getValue(Messages.class);
String message = messages.getMessage();
String from = messages.getFrom();
Log.d("TAG", message + "+" + from);
views.setTextViewText(R.id.appwidget_message, message);
Intent mainIntent = new Intent(ctx, ChatRoomActivity.class);
if(msgReceiverId != null)
mainIntent.putExtra("profile_view_userId", msgReceiverId);
mainIntent.putExtra("username", "Ben");
PendingIntent mainPendingIntent = PendingIntent.getActivity(ctx, REQUEST_CODE, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_layout, mainPendingIntent);
AppWidgetManager.getInstance(ctx).updateAppWidget(new ComponentName(ctx, ProTalkWidget.class), views);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
Please note intent and displaying message works after chatroomactivity has been opened and message sent.
ChatroomActivity
public class ChatRoomActivity extends AppCompatActivity {
private static final String TAG = ChatRoomActivity.class.getSimpleName();
private static final int IMAGE_PICK = 1;
private String msgReceiverId;
private String msgReceiverName;
private static final int TOTAL_ITEMS = 10;
private int currentPage = 1;
private TextView chatUserName;
private TextView chatLastSeen;
private CircleImageView chatProfileImg;
private DatabaseReference rootRef;
private ImageView sendMsgBtn;
private EditText textInputET;
private RecyclerView usersMsgList;
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
//private TabsPagerAdapter.MessagesAdapter messagesAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private int ITEM_POSITION = 0;
private String lastKey;
private String prevKey;
private StorageReference imgStorage;
FirebaseAuth mAuth;
String msgSenderId;
Toolbar appBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES){
setTheme(R.style.darkTheme);
}else{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_chat_room);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
msgSenderId = mAuth.getCurrentUser().getUid();
msgReceiverId = getIntent().getExtras().getString("profile_view_userId");
msgReceiverName = getIntent().getExtras().getString("username");
sendMsgBtn = findViewById(R.id.input_text_btn);
textInputET = findViewById(R.id.input_text);
ProTalkApplication.getInstance().messagesAdapter = new TabsPagerAdapter.MessagesAdapter(messagesList);
usersMsgList = findViewById(R.id.users_messages_list);
linearLayoutManager = new LinearLayoutManager(this);
usersMsgList.setHasFixedSize(true);
usersMsgList.setLayoutManager(linearLayoutManager);
usersMsgList.setAdapter(ProTalkApplication.getInstance().messagesAdapter);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
imgStorage = FirebaseStorage.getInstance().getReference();
fetchMsg();
Intent widgetIntent = new Intent(this,ProTalkWidget.class);
//send value
widgetIntent.putExtra("receiverID", msgReceiverName);
sendBroadcast(widgetIntent);
appBar = findViewById(R.id.chat_appbar);
setSupportActionBar(appBar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View actionBarView = inflater.inflate(R.layout.chat_bar, null);
actionBar.setCustomView(actionBarView);
chatUserName = findViewById(R.id.chat_profile_name);
chatLastSeen = findViewById(R.id.chat_last_seen);
chatProfileImg = findViewById(R.id.chat_profile_img);
chatUserName.setText(msgReceiverName);
sendMsgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMsg();
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
currentPage++;
ITEM_POSITION = 0;
fetchMoreMsg();
}
});
rootRef.child("User").child(msgReceiverId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString().trim();
final String userImg = dataSnapshot.child("thumbnail").getValue().toString();
if (online.equals("true")) {
chatLastSeen.setText(R.string.online);
} else {
GetTimeAgo getTime = new GetTimeAgo();
long lastSeen = Long.parseLong(online);
String lastOnline = getTime.getTimeAgo(lastSeen, getApplicationContext());
//
chatLastSeen.setText(lastOnline);
}
Picasso.get().load(userImg).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.defaultimg).into(chatProfileImg, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(userImg)
.placeholder(R.drawable.defaultimg).into(chatProfileImg);
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void fetchMoreMsg() {
DatabaseReference msgRef = rootRef.child("Messages").child(msgSenderId).child(msgReceiverId);
Query msgQuery = msgRef.orderByKey().endAt(lastKey).limitToLast(10);
msgQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!prevKey.equals(messageKey)) {
messagesList.add(ITEM_POSITION++, messages);
} else {
prevKey = lastKey;
}
if (ITEM_POSITION == 1) {
lastKey = messageKey;
}
ProTalkApplication.getInstance().messagesAdapter.notifyDataSetChanged();
linearLayoutManager.scrollToPositionWithOffset(10, 0);
swipeRefreshLayout.setRefreshing(false);
}
#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(DatabaseError databaseError) {
}
});
}
private void fetchMsg() {
DatabaseReference msgRef = rootRef.child("Messages").child(msgSenderId).child(msgReceiverId);
Query msgQuery = msgRef.limitToLast(currentPage * TOTAL_ITEMS);
msgQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
ITEM_POSITION++;
if (ITEM_POSITION == 1) {
lastKey = messageKey;
prevKey = messageKey;
}
messagesList.add(messages);
ProTalkApplication.getInstance().messagesAdapter.notifyDataSetChanged();
usersMsgList.scrollToPosition(messagesList.size() - 1);
swipeRefreshLayout.setRefreshing(false);
Intent intent = new Intent(ChatRoomActivity.this, ProTalkWidget.class);
intent.setAction(ProTalkWidget.PROTALK_APPWIDGET_UPDATE);
intent.putExtra("senderId", msgSenderId);
intent.putExtra("receiverId", msgReceiverId);
sendBroadcast(intent);
}
#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(DatabaseError databaseError) {
}
});
}
private void sendMsg() {
String msgTxt = textInputET.getText().toString();
if (TextUtils.isEmpty(msgTxt)) {
Toast.makeText(ChatRoomActivity.this, R.string.please_write_a_msg, Toast.LENGTH_SHORT).show();
} else {
String sender_message_ref = "/Messages/" + msgReceiverId + "/" + msgSenderId;
String receiver_message_ref = "/Messages/" + msgSenderId + "/" + msgReceiverId;
DatabaseReference userMsgKey = rootRef.child("Messages").child(msgReceiverId)
.child(msgSenderId).push();
String push_id = userMsgKey.getKey();
Map msgTxtBody = new HashMap();
msgTxtBody.put("message", msgTxt);
msgTxtBody.put("from", msgSenderId);
msgTxtBody.put("seen", false);
msgTxtBody.put("type", "text");
msgTxtBody.put("time", ServerValue.TIMESTAMP);
Map msgBodyDetails = new HashMap();
msgBodyDetails.put(sender_message_ref + "/" + push_id, msgTxtBody);
msgBodyDetails.put(receiver_message_ref + "/" + push_id, msgTxtBody);
rootRef.updateChildren(msgBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d(TAG, databaseError.getMessage().toString());
}
textInputET.setText("");
}
});
}
}
}
Thanks Again!!!

Auto Refresh Doesn't work as i want it to work

I have an Activity called ChatActivity where the users are going to be messaging each other. The activity is retrieving the messages as they are sent but when messages are displayed here are's duplicates of every message.
I do have AutoRefresh but it's not refreshing the way I want it to refresh. In my Activity there is swipe refresh as well and when I swipe it refreshes properly. This is the snap when swipe refresh is used:
How can I make my Auto Refresh display my messages like how it does when I swipe to refresh it? here is my code:
public class ChatActivity extends AppCompatActivity {
private Toolbar mChatToolbar; //used
private String mChatUser; //used
private String mthumb_image;
private String userName;
private String mCurrentUserId;
private TextView mUserStatus;
private EditText mChatMessageView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private ImageButton mChatAddBtn;
private DatabaseReference mRootRef;
// Storage Firebase
private StorageReference mImageStorage;
private static final int GALLERY_PICK = 1;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout;
private ArrayList<Messages> arrayList_Messages = new ArrayList<>();
private MessageAdapter mAdapter;
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatToolbar = (Toolbar) findViewById(R.id.chat_app_bar);
setSupportActionBar(mChatToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
//for Custom Action bar
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View customBar = inflater.inflate(R.layout.chat_custom_bar,null);
actionBar.setCustomView(customBar);
//getting intent Data
gettingIntentData();
// initializing user view
intCustomBarViewAndSetData();
doTheAutoRefresh();
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
//------- IMAGE STORAGE ---------
mImageStorage = FirebaseStorage.getInstance().getReference();
mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue(true);
LoadMessages();
//getting information about user online or offline and thumb image
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
Picasso.with(ChatActivity.this).load(thumb_image).placeholder(R.drawable.my_profile).into(mProfileImage);
String lastSeen = dataSnapshot.child("online").getValue().toString();
if(lastSeen.equals("true")){
mUserStatus.setText("Online");
}
else{
//converting string into long
Long lastTime = Long.parseLong(lastSeen);
// creating an instance of GetTimeAgo class
GetTimeAgo getTimeAgo = new GetTimeAgo();
String lastSeenTime = GetTimeAgo.getTimeAgo(lastTime,getApplicationContext());
mUserStatus.setText(lastSeenTime);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//for creating chat object
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
chatUserMap.put("Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(ChatActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Retrieving the chat messages into recyclerview
LoadMessages();
mRefreshLayout.setRefreshing(true);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
//onRefresh remove the current messages from arraylist and load new messages
arrayList_Messages.clear();
// Load message
LoadMessages();
}
});
}
private void doTheAutoRefresh()
{
handler.postDelayed(new Runnable() {
#Override
public void run()
{
LoadMessages();
// Write code for your refresh logic
doTheAutoRefresh();
}
}, 5000);
}
// Load all messages from database into recyclerView
private void LoadMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
//Query to load message per page i.e. 10
/*
per page load 10 message and onRefresh mCurrentpage is increment by 1
page 1 => load 10 messages (mCurrentPage = 1 then 1*10 =10)
page 2 => load 20 messages (mCurrentPage = 2 then 2*10 =20) and so on
*/
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
arrayList_Messages.add(messages);
mRefreshLayout.setRefreshing(true);
mAdapter.notifyDataSetChanged();
mMessagesList.scrollToPosition(arrayList_Messages.size()-1);
//when data load completely set refreshing
mRefreshLayout.setRefreshing(false);
}
#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(DatabaseError databaseError) {
}
});
}
// send button
public void chatSendButton(View view){
sendMessage();
}
//sending a message
private void sendMessage() {
String message = mChatMessageView.getText().toString().trim();
if(!TextUtils.isEmpty(message)){
mChatMessageView.setText("");
String current_user_ref="messages/"+mCurrentUserId+"/"+mChatUser;
String chat_user_ref= "messages/"+mChatUser+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("messages").child(mCurrentUserId).
child(mChatUser).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("message",message);
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
}
//add button
public void chatAddButton(View view){
mChatAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
final String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();
final String push_id = user_message_push.getKey();
StorageReference filepath = mImageStorage.child("message_images").child( push_id + ".jpg");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
String download_url = task.getResult().getDownloadUrl().toString();
Map messageMap = new HashMap();
messageMap.put("message", download_url);
messageMap.put("seen", false);
messageMap.put("type", "image");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from", mCurrentUserId);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.setText("");
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
});
}
}
private void intCustomBarViewAndSetData() {
TextView mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mUserStatus = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mMessagesList.setLayoutManager(new LinearLayoutManager(this));
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
mMessagesList.setHasFixedSize(true);
mAdapter = new MessageAdapter(this, arrayList_Messages);
mMessagesList.setAdapter(mAdapter);
//showing name on toolbar
mTitleView.setText(userName);
mTitleView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(ChatActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_id", mChatUser);
startActivity(profileIntent);
}
});
}
private void gettingIntentData() {
Intent intent =getIntent();
userName = intent.getStringExtra("Username");
mChatUser = intent.getStringExtra("user_id");
}
}
Clear the list before load in doTheAutoRefresh().
arrayList_Messages.clear();
LoadMessages();

Categories