So basically I have implemented a fragment for my app using firebase Recycler Adapter. I have searched through out the internet to hide a row in the recycler view without occupying white space. I have applied various people solutions but result is same.
My Fragment code is like this:
public class RequestFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_request, container, false);
mReqList = (RecyclerView) mMainView.findViewById(R.id.req_list);
mRootRef =FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser() !=null)
mCurrent_user_id = mAuth.getCurrentUser().getUid();
if(mCurrent_user_id !=null) {
mReqDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req").child(mCurrent_user_id);
mReqDatabase.keepSynced(true);
}
text = (TextView) mMainView.findViewById(R.id.request_fragment_text);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mReqList.setHasFixedSize(true);
mReqList.setLayoutManager(linearLayoutManager);
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
if(mReqDatabase != null) {
final Query requestQuery = mReqDatabase.orderByChild("request_type");
FirebaseRecyclerAdapter<Request, RequestFragment.ReqViewHolder> firebaseReqAdapter = new FirebaseRecyclerAdapter<Request, RequestFragment.ReqViewHolder>(
Request.class,
R.layout.single_request_layout,
ReqViewHolder.class,
requestQuery
) {
#Override
protected void onDataChanged() {
if(getItemCount() == 0){
text.setText("No New Friend Request");
}
else{
text.setText("");
}
}
#Override
protected void populateViewHolder(final RequestFragment.ReqViewHolder reqViewHolder, final Request req, int i) {
final String list_user_id = getRef(i).getKey();
mAcceptBtn = reqViewHolder.mView.findViewById(R.id.single_req_accept_btn2);
mDeclineBtn = reqViewHolder.mView.findViewById(R.id.single_req_decline_btn);
if (req.getRequest_type().equals("received")) {
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
text.setText("");
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
reqViewHolder.setUserOnline(userOnline);
}
reqViewHolder.setName(userName);
reqViewHolder.setUserImage(userThumb, getContext());
mAcceptBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Friends/" + mCurrent_user_id + "/" + list_user_id + "/date", currentDate);
friendsMap.put("Friends/" + list_user_id + "/" + mCurrent_user_id + "/date", currentDate);
friendsMap.put("Friend_req/" + mCurrent_user_id + "/" + list_user_id, null);
friendsMap.put("Friend_req/" + list_user_id + "/" + mCurrent_user_id, null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
reqViewHolder.mView.setVisibility(View.INVISIBLE);
} else {
String error = databaseError.getMessage();
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
});
mDeclineBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Friend_req/" + mCurrent_user_id + "/" + list_user_id, null);
friendsMap.put("Friend_req/" + list_user_id + "/" + mCurrent_user_id, null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
reqViewHolder.mView.setVisibility(View.INVISIBLE);
} else {
String error = databaseError.getMessage();
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
reqViewHolder.Invisible();
text.setText("No New Friend Request");
}
}
};
mReqList.setAdapter(firebaseReqAdapter);
}
}
public static class ReqViewHolder extends RecyclerView.ViewHolder {
View mView;
public ReqViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setStatus(String status) {
TextView fragmentStatus = mView.findViewById(R.id.request_fragment_text);
fragmentStatus.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.req_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.req_single_image);
Picasso.get().load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.req_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
public void Invisible(){
mView.setVisibility(View.INVISIBLE);
}
}
}
My fragment in the app is looking like this:
Can anyone help me how to get rid of this white space?
Related
I'm creating a social messaging app.
the ideal on how the app function is where the messages are saved to the firebase database and then displayed on the RecyclerView.. the messages are saved to the database but not displayed on the RecyclerView.
please help...
thank you
message adopter class.
public class MessagesAdopter extends RecyclerView.Adapter {
public MessagesAdopter(List<Messages> messagesList) {
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
public class MessageAdopter extends RecyclerView.Adapter<MessageAdopter.MessageViewHolder> {
private List<Messages> usersmessengeslist;
private FirebaseAuth mAuth;
private DatabaseReference userdatabaseref;
public MessageAdopter (List<Messages> usersmessengeslist){
this.usersmessengeslist = usersmessengeslist;
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
private TextView sender_typed_message,reciever_typed_message;
CircleImageView reciever_image_view;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
sender_typed_message = itemView.findViewById(R.id.sender_typed_message);
reciever_typed_message = itemView.findViewById(R.id.reciever_typed_message);
reciever_image_view = itemView.findViewById(R.id.reciver_profile_image);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_message_layout,parent ,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, int position) {
String messagesenderid = mAuth.getCurrentUser().getUid();
Messages messages = usersmessengeslist.get(position);
String fromUserID = messages.getFrom();
String frommessagetype = messages.getType();
userdatabaseref = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
userdatabaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String image = dataSnapshot.child("profileimage").getValue(String.class);
Picasso.get().load(image).placeholder(R.drawable.profile).into(holder.reciever_image_view);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (frommessagetype.equals("text")){
holder.reciever_image_view.setVisibility(View.INVISIBLE);
holder.reciever_typed_message.setVisibility(View.INVISIBLE);
if (fromUserID.equals(messagesenderid)){
holder.sender_typed_message.setBackgroundResource(R.drawable.sender_message_background);
holder.sender_typed_message.setTextColor(Color.WHITE);
holder.sender_typed_message.setGravity(Gravity.LEFT);
holder.sender_typed_message.setText(messages.getMessage());
}
else
{
holder.sender_typed_message.setVisibility(View.INVISIBLE);
holder.reciever_typed_message.setVisibility(View.VISIBLE);
holder.reciever_image_view.setVisibility(View.VISIBLE);
holder.reciever_typed_message.setBackgroundResource(R.drawable.reciever_message_background);
holder.reciever_typed_message.setTextColor(Color.WHITE);
holder.reciever_typed_message.setGravity(Gravity.LEFT);
holder.reciever_typed_message.setText(messages.getMessage());
}
}
}
#Override
public int getItemCount() {
return usersmessengeslist.size();
}
}
}
chat activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
messagesenderuserIdD = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
recievereruserid = getIntent().getExtras().get("visit_user_id").toString();
recieverrusername = getIntent().getExtras().get("userName").toString();
iniitializefeildz();
displayrecieveruserinformtion();
sendmessagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendusermessage();
}
});
fetchmessage();
}
private void fetchmessage() {
RootRef.child("Messages").child(messagesenderuserIdD).child(recievereruserid)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
mMessagesList.add(messages);
MessagesAdopter.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) {
}
});
}
private void sendusermessage() {
String messagetext = user_inout_message.getText().toString();
if (TextUtils.isEmpty(messagetext)){
Toast.makeText(chatActivity.this,"please type a message",Toast.LENGTH_SHORT).show();
}
else {
String message_sender_ref = "Messages/" + messagesenderuserIdD + "/" + recievereruserid;
String message_reciever_ref = "Messages/" + recievereruserid + "/" + messagesenderuserIdD;
DatabaseReference user_message_key = RootRef.child("Message").child(messagesenderuserIdD).child(recievereruserid).push();
String message_push_id =user_message_key.getKey();
Calendar callforddate = Calendar.getInstance();
SimpleDateFormat currentdate =new SimpleDateFormat("dd-MMMM-yyyy");
savecurrentdate= currentdate.format(callforddate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
savecurrenttime = currentTime.format(callforddate.getTime());
Map messageTextbody = new HashMap();
messageTextbody.put("Message", messagetext);
messageTextbody.put("time", savecurrenttime);
messageTextbody.put("date", savecurrentdate);
messageTextbody.put("type", "text");
messageTextbody.put("from", messagesenderuserIdD);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/"+ message_push_id,messageTextbody);
messageBodyDetails.put(message_reciever_ref + "/"+ message_push_id,messageTextbody);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(chatActivity.this,"message sent successfully",Toast.LENGTH_SHORT).show();
user_inout_message.setText("");
}
else {
String message = task.getException().getMessage();
Toast.makeText(chatActivity.this,"Error" + message,Toast.LENGTH_SHORT).show();
user_inout_message.setText("");
}
}
});
}
}
private void displayrecieveruserinformtion() {
chat_username.setText(recieverrusername);
RootRef.child("Users").child(recievereruserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String profileimage = dataSnapshot.child("profileimage").getValue(String.class);
Picasso.get().load(profileimage).placeholder(R.drawable.profile).into(chat_circular_imageview);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void iniitializefeildz() {
mToolbar = findViewById(R.id.action_cjat_bar);
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_appbar,null);
actionBar.setCustomView(action_bar_view);
chat_username = findViewById(R.id.user_chat_displayname);
chat_circular_imageview = findViewById(R.id.user_chat_displayimage);
user_inout_message= findViewById(R.id.chat_write_message_here);
sendmessagebutton = findViewById(R.id.send_chat_message);
sendimagemessage = findViewById(R.id.chat_chooseimage);
MessagesAdopter = new MessagesAdopter(mMessagesList);
messagesview = findViewById(R.id.messageview_list);
linearlayoutmanager = new LinearLayoutManager(this);
messagesview.setHasFixedSize(true);
messagesview.setLayoutManager(linearlayoutmanager);
messagesview.setAdapter(MessagesAdopter);
}
}
hi i am fatching my massages from firebase database with this, try this it will help you :-
private void readMessage(final String myId, final String userId) {
mChat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference(chatTableName);
try {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
Chat chat = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
chat = snapshot.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userId) ||
chat.getReceiver().equals(userId) && chat.getSender().equals(myId)) {
mChat.add(chat);
}
adapter = new MessageAdapter(UserMessageActivity.this, mChat);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (Exception e) {
Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I was following a tutorial on youtube to make a chat app and this fragment shows the list of friends but this method cant be used anymore. I have tried my whole night putting up the code together but couldn't.
public class FriendsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.friends_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
// I have tried using options here but i failed*
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(
Friends.class,
R.layout.users_single_layout,
FriendsViewHolder.class,
mFriendsDatabase
) {
// This method is no more available
#Override
protected void populateViewHolder(final FriendsViewHolder friendsViewHolder, Friends friends, int i) {
friendsViewHolder.setDate(friends.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", list_user_id);
startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(friendsRecyclerViewAdapter);
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(date);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
I'm new to android and I wanted to create a chat in my app, it's like a global roomchat based on firebase. Messages are displayed via RecyclerView and the problem is that when it's loaded the images of people, their names are somehow mixed up. When I go back to previous activity and open the chat activity again everything becomes OK. But the when a new message is added the rows shuffle again. I'm sure that it should be very ease to fix, but I can't...Please help. Thank you!
This is the chat activity oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_chat);
main_recycler_view = (RecyclerView) findViewById(R.id.messages_list);
main_recycler_view.setVisibility(View.GONE);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
}
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
sendToStart();
} else {
mUserRef.child("online").setValue("true");
String transp = "https://firebasestorage.googleapis.com/v0/b/chatqs-a4c10.appspot.com/o/profile_images%2Ftransp.png?alt=media&token=fc7b2315-f24b-453a-926e-364fff55e31b";
mUserRef.child("version").setValue(transp);
mToolbar = (Toolbar) findViewById(R.id.chattb);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.chat_title);
imageButton_send = (Button) findViewById(R.id.chat_send_btn);
editText_message = (EditText) findViewById(R.id.chat_message_view);
database = FirebaseDatabase.getInstance();
databaseRef = database.getReference();
mContext = (MainChatPage.this);
adapter = new MainAdapter(mContext, messageArrayList);
main_recycler_view.setAdapter(adapter);
main_recycler_view.setLayoutManager(new LinearLayoutManager(c));
databaseRef.child("the_messages").limitToLast(50).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
progressBar.setVisibility(View.GONE);
main_recycler_view.setVisibility(View.VISIBLE);
final Message new_message = dataSnapshot.getValue(Message.class);
final String userid = dataSnapshot.child("userID").getValue().toString();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userid).exists()) {
messageArrayList.remove(new_message);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
main_recycler_view.scrollToPosition(adapter.getItemCount() - 1);
messageArrayList.add(new_message);
adapter.notifyDataSetChanged();
}
#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) {
}
});
My adapter:
public MainAdapter(MainChatPage context, ArrayList<Message> data) {
this.data = data;
this.mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_single_layout, null);
message_profile_layout = (CircleImageView) view.findViewById(R.id.message_profile_layout);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {
final Message message = data.get(i);
final String userid = message.getUserID();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String thumb = dataSnapshot.child("thumb_image").getValue().toString();
String nome = dataSnapshot.child("name").getValue().toString();
String dialog_name = nome;
String vers = dataSnapshot.child("version").getValue().toString();
//String proic = "https://firebasestorage.googleapis.com/v0/b/chatqs-a4c10.appspot.com/o/profile_images%2Ficonfinder-pro-icon-icon.png?alt=media&token=1ca05e32-f3e7-4f73-af54-2be17ad0fed6";
// Picasso.with(myViewHolder.mes_proicon.getContext()).load(proic)
// .placeholder(R.drawable.transp).into(myViewHolder.mes_proicon);
// myViewHolder.name_text_layout.setText(nome);
Picasso.with(myViewHolder.message_profile_layout.getContext()).load(thumb)
.placeholder(R.drawable.default_avatar).into(myViewHolder.message_profile_layout);
Picasso.with(myViewHolder.mes_proicon.getContext()).load(vers)
.placeholder(R.drawable.transp).into(myViewHolder.mes_proicon);
myViewHolder.name_text_layout.setText(nome);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
String formatted_date = SCUtils.formatted_date(message.getTimestamp());
myViewHolder.message_text_layout.setText(Html.fromHtml(message.getMessage()));
myViewHolder.time_text_layout.setText(Html.fromHtml(formatted_date));
myViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userid.equals(current_uid)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
LayoutInflater inflater = mContext.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog, null);
TextView dialog_name = (TextView) dialogView.findViewById(R.id.dialog_name);
CircleImageView dialog_icon = (CircleImageView) dialogView.findViewById(R.id.dialog_icon);
builder.setView(dialogView);
dialog_name.setText(myViewHolder.name_text_layout.getText());
dialog_icon.setImageDrawable(myViewHolder.message_profile_layout.getDrawable());
builder.setPositiveButton(R.string.block, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
mDatabase.child(userid).push().setValue("");
}
})
.setNegativeButton(R.string.open_profile, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent chatIntent = new Intent(mContext, UserProfileActivity.class);
chatIntent.putExtra("user_id", userid);
mContext.startActivity(chatIntent);
mContext.finish();
}
});
builder.show();
} else {
Intent Intent = new Intent(mContext, ProfileFragment.class);
mContext.startActivity(Intent);
mContext.finish();
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
View mView;
protected TextView message_text_layout;
protected TextView name_text_layout;
protected TextView time_text_layout;
protected CircleImageView message_profile_layout;
protected CircleImageView mes_proicon;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
this.message_text_layout = (TextView) mView.findViewById(R.id.message_text_layout);
this.name_text_layout = (TextView) mView.findViewById(R.id.name_text_layout);
this.time_text_layout = (TextView) mView.findViewById(R.id.time_text_layout);
this.mes_proicon = (CircleImageView) mView.findViewById(R.id.mes_proicon);
this.message_profile_layout = (CircleImageView) mView.findViewById(R.id.message_profile_layout);
}
}
just remove .placeholder. I dont know why but sometimes it happens because of this method
There is my activity:
public class EventDetailsActivity extends AppCompatActivity {
private Event event;
private ArrayList<User> subscribedUsers;
private RecyclerView mRecyclerView;
private String eventId;
private SubscribedUsersAdapter adapter;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
context = this;
Bundle extras = getIntent().getExtras();
eventId = extras.getString("eventId");
setUpEvent();
}
private void setUpEvent() {
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(eventId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventType = dataSnapshot.child("eventType").getValue().toString();
String description = dataSnapshot.child("description").getValue().toString();
Object object = dataSnapshot.child("startingDate").getValue();
HashMap result = (HashMap) object;
int year = Integer.parseInt(result.get("year").toString());
int month = Integer.parseInt(result.get("month").toString());
int day = Integer.parseInt(result.get("date").toString());
int hour = Integer.parseInt(result.get("hours").toString());
int minute = Integer.parseInt(result.get("minutes").toString());
Date startingDate = new Date(year,month,day,hour,minute,0);
object = dataSnapshot.child("location").getValue();
result = (HashMap) object;
double latitude = Double.parseDouble(result.get("latitude").toString());
double longitude = Double.parseDouble(result.get("longitude").toString());
LatLng location = new LatLng(latitude,longitude);
String userId = dataSnapshot.child("userId").getValue().toString();
String userName = dataSnapshot.child("userName").getValue().toString();
String userPicture = dataSnapshot.child("userPicture").getValue().toString();
subscribedUsers = new ArrayList<User>();
if (dataSnapshot.hasChild("subscribedUsers")) {
mDatabase.child("subscribedUsers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
event = new Event(eventId, eventType,description,startingDate,location,userId, userName, userPicture);
setText();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setText()
{
ImageView mProfilePicture = (ImageView) findViewById(R.id.profilePicture);
if (!EventDetailsActivity.this.isFinishing()) {
Glide
.with(this)
.load(event.getUserPicture())
.into(mProfilePicture);
}
TextView mUserName = (TextView) findViewById(R.id.userName);
mUserName.setText(event.getUserName());
TextView mEventType = (TextView) findViewById(R.id.eventType);
mEventType.setText(event.getEventType());
TextView mDescription = (TextView) findViewById(R.id.description);
mDescription.setText(event.getDescription());
if (!EventDetailsActivity.this.isFinishing()) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(new OnMapReadyCallback()
{
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.clear();
googleMap.addMarker(new MarkerOptions().position(event.getLocation()));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(event.getLocation(),12.0f));
}
});
}
TextView mStartingDate = (TextView) findViewById(R.id.startingDate);
Date startingDate = event.getStartingDate();
String displayText = String.valueOf(startingDate.getYear());
int month = startingDate.getMonth() + 1;
if (month/10 == 0)
{
displayText = displayText + ".0" + month;
}
else
{
displayText = displayText + "." + month;
}
if (startingDate.getDate()/10 == 0)
{
displayText = displayText + ".0" + startingDate.getDate();
}
else
{
displayText = displayText + "." + startingDate.getDate();
}
if (startingDate.getHours()/10 == 0)
{
displayText = displayText + ". 0" + startingDate.getHours();
}
else
{
displayText = displayText + ". " + startingDate.getHours();
}
if (startingDate.getMinutes()/10 == 0)
{
displayText = displayText + ":0" + startingDate.getMinutes();
}
else
{
displayText = displayText + ":" + startingDate.getMinutes();
}
mStartingDate.setText(displayText);
setUpRecyclerView();
subscribe();
}
private void setUpRecyclerView() {
adapter = new SubscribedUsersAdapter(this,subscribedUsers);
mRecyclerView.setAdapter(adapter);
}
private void subscribe()
{
FirebaseAuth mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
final String userId = mAuth.getCurrentUser().getUid();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("name").getValue().toString();
String userPicture = dataSnapshot.child("picture").getValue().toString();
User user = new User(userId, userName, userPicture);
userSubscribe(user);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
userSubscribe(null);
}
}
private void userSubscribe(final User user) {
Button mSubscribeButton = (Button) findViewById(R.id.subscribeButton);
if (user == null)
{
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(EventDetailsActivity.this, getResources().getString(R.string.logInToSubscribe), Toast.LENGTH_LONG).show();
Intent loginIntent = new Intent(EventDetailsActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
});
}
else if (containsUser(subscribedUsers,user) == -1)
{
mSubscribeButton.setText(getResources().getString(R.string.subscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
subscribedUsers.add(user);
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
else
{
mSubscribeButton.setText(getResources().getString(R.string.unsubscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
int position = containsUser(subscribedUsers,user);
subscribedUsers.remove(position);
mDatabase.child("subscribedUsers").removeValue();
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
private int containsUser(ArrayList<User> users, User user)
{
for (int i=0; i<users.size(); ++i)
{
if (users.get(i).getUserId().equals(user.getUserId()))
{
return i;
}
}
return -1;
}
}
And my adapter:
public class SubscribedUsersAdapter extends RecyclerView.Adapter<SubscribedUsersAdapter.ViewHolder>{
private Context context;
private ArrayList<User> items;
public SubscribedUsersAdapter(Context context, ArrayList<User> items) {
this.context = context;
this.items = items;
}
protected static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mProfilePictureView;
public TextView mUserName;
public ViewHolder(View itemView) {
super(itemView);
mProfilePictureView = (ImageView) itemView.findViewById(R.id.profilePictureView);
mUserName = (TextView) itemView.findViewById(R.id.userName);
}
}
#Override
public SubscribedUsersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final User item = items.get(position);
Glide
.with(context)
.load(item.getPicture())
.into(holder.mProfilePictureView);
holder.mUserName.setText(item.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(context, ProfileActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
profileIntent.putExtra("userId", item.getUserId());
context.startActivity(profileIntent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
}
When the activity starts firstly, the data is displayed well in RecyclerView, but if a user subscribes to the event or unsubscribe from it, the RecyclerView will be empty.
I tried with notifyDataSetChanged, notifyItemRangeInserted, notifyItemRangeRemoved, but none of them worked or I didn't use it well. I don't know.
Thanks for your help!
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
after that just add this line
adapter.notifyDataSetChanged();
I am beginner at Android app development and I have created a chat app using Firebase database. I am using two Android phones to test the app, Android Samsung 4.4.2 API 19 and Samsung 5.0.1 API 21. The app used to work fine on both phones. I added some lines in the CharActivity for notification purpose, I ran the app, it worked fine on Android Samsung 4.4.2 API 19, but crashes on Samsung 5.0.1 API 21 at the lunch. So I undo all the changes I made until the point where my app was working fine on Samsung 5.0.1 API 21. But the surprise is it still crashes!
Now I am facing a problem with the Samsung 5.0.1 API 21. Every time I run the app it crashes at the lunch, and here is the problem I get.
FATAL EXCEPTION: main
Process: com.example.maalialabdulhafith.nfc_mac, PID: 30357
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Please note that my other Android Samsung 4.4.2 API 19 works fine and doesn't crash.
FriendsFragment Class (Where all my friends are listed)
public class FriendsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.friends_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(
Friends.class,
R.layout.users_single_layout,
FriendsViewHolder.class,
mFriendsDatabase
) {
#Override
protected void populateViewHolder(final FriendsViewHolder friendsViewHolder, Friends friends, int i) {
//friendsViewHolder.setDate(friends.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
final String userStatus = dataSnapshot.child("status").getValue().toString(); // I added this
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.setUserStatus(userStatus); //<== if you want to show status instead of date
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", list_user_id);
startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(friendsRecyclerViewAdapter);
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
/*public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(date);
}*/
//if you want to display the statuse instead of the date, activite this and comment setDate method
public void setUserStatus(String status) {
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}
Chat Class
public class ChatActivity extends AppCompatActivity {
// user id whom we want to chat with
private String mChatUser;
private DatabaseReference mRootRef;
private TextView mTitleView;
private TextView 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; // For Pagination
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager mLinearLayout;
private MessageAdapter mAdapter;
// For Pagination
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private int itemPos = 0;
private String mLastKey = "";
private String mPrevKey = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat2);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
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);
// to display the image in the bar
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(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);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout); // pagenation
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
mMessagesList.setAdapter(mAdapter);
loadMessages();
mTitleView.setText(userName);
// showing last time was seen
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
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);
}
//CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.custom_bar_image);
//Picasso.with(i).load(image).placeholder(R.drawable.default_avatar).into(userImageView);
//Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
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){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
// Swipe/Pull to Refresh for Android RecyclerView
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
itemPos = 0;
loadMoreMessages();
}
});
}
// ------------------ LOAD More Messages ------------------
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(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!mPrevKey.equals(messageKey)){
messagesList.add(itemPos++, message);
} else{
mPrevKey=mLastKey;
}
if (itemPos == 1){
mLastKey = messageKey;
}
Log.d("TOTALKEYS", "Last Key: " + mLastKey + "| Prev Key: " + mPrevKey + "| Message Key: " + messageKey );
mAdapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
mLinearLayout.scrollToPositionWithOffset(10,0);
}
#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) {
}
});
}
// ------------------ LOAD Messages ------------------
private void loadMessages() {
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(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
itemPos++;
if (itemPos == 1){
String messageKey = dataSnapshot.getKey();
mLastKey = messageKey;
mPrevKey = messageKey;
}
messagesList.add(message);
mAdapter.notifyDataSetChanged();
mMessagesList.scrollToPosition(messagesList.size () -1);
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) {
}
});
}
private void sendMessage() {
String message = mChatMessageView.getText().toString();
if(!TextUtils.isEmpty(message)){
String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();
String push_id = user_message_push.getKey();
Map messageMap = new HashMap();
messageMap.put("message", message);
messageMap.put("seen", false);
messageMap.put("type", "text");
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());
}
}
});
}
}
}
What doesn't make sense to me is, how does it run on one device and doesn't on other? I would appreciate a detailed answer. Thanks in advance!
Acknowledgment: I have learned this code from the amazing TVAC Studio on Youtube.
The user is not signed-in.
Change your code to the following
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null && !firebaseUser.getUid().isEmpty()) {
// all OK
} else {
// repeat the authentication process again
}
As explained by tim4dev, you havent logged in using any specific user. If you havent created a user, go to the firebase console and allow a signup type. They are like email and password auth, phone number auth, anonymous, etc. Once you have enabled one of the options, you can sign up using the auth class and sign in / login afterwards. Once you login with a user account on a device, only then will the
mCurrent_user_id = mAuth.getCurrentUser().getUid();
statement work and return a non-null id.
Hope it solves the problem.