visually duplicating existing record when deleted/updated record - android

does anyone here encountered when you are updating a data it duplicates the existing data visually only but when I will back and go to the activity again it shows the real data.
Data 1 and Data 2, when I delete Data 2, it will show Data 1 Data2 and Data 1. However like I said, it is just visual had to go back and go to the activity again to show the current data which is Data 1 only since Data 2 has been deleted. I have tried searching but none of them are related to my problem and I genuinely do not know if this is from the database or the card or in the recyclerview. Any help will be much appreciated.
MainActivity
public class AdminReqFormsActivity extends AppCompatActivity {
RecyclerView adminreqform_recycler;
ImageView adminreqfromfield_backbtn;
DatabaseReference databaseReference;
ArrayList<ResearchReqForm> reqFormArrayList;
AdminRequestFormAdapter adminRequestFormAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_req_forms);
adminreqform_recycler = findViewById(R.id.adminreqform_recycler);
adminreqfromfield_backbtn = findViewById(R.id.adminreqfromfield_backbtn);
databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRequest");
adminreqform_recycler.setLayoutManager(new LinearLayoutManager(this));
reqFormArrayList = new ArrayList<ResearchReqForm>();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ResearchReqForm researchReqForm = dataSnapshot.getValue(ResearchReqForm.class);
reqFormArrayList.add(researchReqForm);
}
adminRequestFormAdapter = new AdminRequestFormAdapter(AdminReqFormsActivity.this, reqFormArrayList);
adminreqform_recycler.setAdapter(adminRequestFormAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminReqFormsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
adminreqfromfield_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
}
}
Model
public class ResearchReqForm {
String studentName;
String requestedtitle;
String requestedtags;
String requestMessage;
String requestid;
String requestStatus;
public ResearchReqForm() {
}
public ResearchReqForm(String studentName, String requestedtitle, String requestedtags, String requestMessage, String requestid, String requestStatus) {
this.studentName = studentName;
this.requestedtitle = requestedtitle;
this.requestedtags = requestedtags;
this.requestMessage = requestMessage;
this.requestid = requestid;
this.requestStatus = requestStatus;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getRequestedtitle() {
return requestedtitle;
}
public void setRequestedtitle(String requestedtitle) {
this.requestedtitle = requestedtitle;
}
public String getRequestedtags() {
return requestedtags;
}
public void setRequestedtags(String requestedtags) {
this.requestedtags = requestedtags;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public String getRequestid() {
return requestid;
}
public void setRequestid(String requestid) {
this.requestid = requestid;
}
public String getRequestStatus() {
return requestStatus;
}
public void setRequestStatus(String requestStatus) {
this.requestStatus = requestStatus;
}
}
Adapter
public class AdminRequestFormAdapter extends RecyclerView.Adapter<AdminRequestFormAdapter.AdminRequestFormViewHolder> {
Context context;
ArrayList<ResearchReqForm> requestFormArrayList;
public AdminRequestFormAdapter(Context c, ArrayList<ResearchReqForm> reqFormsList){
context = c;
requestFormArrayList = reqFormsList;
}
#NonNull
#Override
public AdminRequestFormViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminRequestFormAdapter.AdminRequestFormViewHolder(LayoutInflater.from(context).inflate(R.layout.admin_request_list,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminRequestFormViewHolder holder, final int position) {
holder.adminsudentname_reqcv.setText(requestFormArrayList.get(position).getStudentName());
holder.adminrelatedtopic_requestcv.setText(requestFormArrayList.get(position).getRequestedtitle());
holder.admintopictags_requestcv.setText(requestFormArrayList.get(position).getRequestedtags());
holder.adminbriefmessage_reqeuestcv.setText(requestFormArrayList.get(position).getRequestMessage());
holder.deleteresearch_request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Delete Request Research?");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRequest");
final String uniqueKey = requestFormArrayList.get(position).getRequestid();
databaseReference.child(uniqueKey).removeValue();
Toast.makeText(context, "Student's Request has been deleted.", Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Form Closed.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
alert.show();
}
});
holder.acceptresearch_request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Test Toast For Accept", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return requestFormArrayList.size();
}
class AdminRequestFormViewHolder extends RecyclerView.ViewHolder{
TextView adminsudentname_reqcv, adminrelatedtopic_requestcv, admintopictags_requestcv, adminbriefmessage_reqeuestcv;
Button deleteresearch_request, acceptresearch_request;
public AdminRequestFormViewHolder(#NonNull View itemView) {
super(itemView);
adminsudentname_reqcv = itemView.findViewById(R.id.adminsudentname_reqcv);
adminrelatedtopic_requestcv =itemView.findViewById(R.id.adminrelatedtopic_requestcv);
admintopictags_requestcv = itemView.findViewById(R.id.admintopictags_requestcv);
adminbriefmessage_reqeuestcv = itemView.findViewById(R.id.adminbriefmessage_reqeuestcv);
deleteresearch_request = itemView.findViewById(R.id.deleteresearch_request);
acceptresearch_request = itemView.findViewById(R.id.acceptresearch_request);
}
}
}

Yes, this is actually quite common and comes from a misunderstanding of how Firebase snapshots work.
Whenever your onDataChange is called it gets a full snapshot of all the data at databaseReference. So even if there's only one change since you rendered the data, you get called with a full snapshot of all data at databaseReference including the change. And since you add all data in snapshot to reqFormArrayList, you end up duplicating it each time onDataChange gets called.
The simplest solution is to clear reqFormArrayList inside onDataChange:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
reqFormArrayList.clear(); // this is the new line
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ResearchReqForm researchReqForm = dataSnapshot.getValue(ResearchReqForm.class);
reqFormArrayList.add(researchReqForm);
}
adminRequestFormAdapter = new AdminRequestFormAdapter(AdminReqFormsActivity.this, reqFormArrayList);
adminreqform_recycler.setAdapter(adminRequestFormAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminReqFormsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
})

Related

when deleting a filtered Item in a Recyclerview it reappears, how do I avoid this?

I have a Recyclerview which has a search bar at the top to filter by "rut", but when filtering an item and then deleting it by pressing the red trash button, the item reappears when leaving the filter field empty again, I understand that It happens because the filter keeps a temporary array of the data, but how can I get the new list anyway if I delete an item? I have tried several ways but I could not solve it (if I reload the activity it is possible to see that the item was removed and it does not come out again)
left a sequence of photos of the procedure that I comment.
in the first photo there is a list of 3 items
in the second I filter by the rut "098"
in the third I remove the filtered item "098"
in the fourth I no longer There is this item
but in the fifth, when eliminating what is written in the edittext (filter), the item "098" appears again and it brings company, because the items are duplicated
Code of Adapter
#Override
public void onBindViewHolder(#NonNull PacientesviewHolder holder, int position) {
Pacientes paciente = list.get(position);
holder.cv.setAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_transition));
holder.textViewRut.setText(paciente.getRut());
holder.textViewNombre.setText(paciente.getNombre());
holder.textViewApellidos.setText(paciente.getApellidos());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference() // Firebase reference to after remove item
.child("Pacientes"+userID_S)
.child(paciente.getKey());
new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_warning)
.setTitle("¿Seguro desea borrar a este paciente?") // to confirm deletion
.setCancelable(false)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int newPosition = holder.getAdapterPosition();
list.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, list.size());
ref.removeValue();
list.clear();
notifyDataSetChanged();
}
}).show();
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(paciente);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class PacientesviewHolder extends RecyclerView.ViewHolder {
TextView textViewRut, textViewNombre, textViewApellidos;
CardView cv;
ImageView delete;
public PacientesviewHolder(#NonNull View itemView) {
super(itemView);
textViewRut = itemView.findViewById(R.id.textview_rut);
textViewNombre = itemView.findViewById(R.id.textview_nombre);
textViewApellidos = itemView.findViewById(R.id.textview_apellidos);
cv = itemView.findViewById(R.id.cv);
delete = itemView.findViewById(R.id.ic_delete);
}
}
public void filterList(ArrayList<Pacientes> filteredList) { // Filter
list = filteredList;
notifyDataSetChanged();
}
}
Code where the recycler view is shown and where the filter is
public class mostrarActivity extends AppCompatActivity {
RecyclerView recyclerPa;
DatabaseReference database;
Adapter adapter;
public ArrayList<Pacientes> list;
String userID, userID_S;
EditText editSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mostrar);
ocultarUpBar();
userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
userID_S = userID.substring(0,5);
recyclerPa = findViewById(R.id.RecyclerPa);
database = FirebaseDatabase.getInstance().getReference("Pacientes"+userID_S);
recyclerPa.setHasFixedSize(true);
recyclerPa.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new Adapter(this, list, new Adapter.OnItemClickListener() {
#Override
public void onItemClick(Pacientes item) {
move(item);
}
});
recyclerPa.setAdapter(adapter);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Pacientes pacientes = dataSnapshot.getValue(Pacientes.class);
pacientes.setKey(dataSnapshot.getKey());
list.add(pacientes);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
editSearch = findViewById(R.id.editSearch);
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
}
// Funciones
private void filter(String text) {
ArrayList<Pacientes> filteredList = new ArrayList<>();
for (Pacientes item : list) {
if (item.getRut().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
adapter.filterList(filteredList);
}
public void move(Pacientes item){
Intent intent = new Intent(this, FichaPacientes_Activity.class);
intent.putExtra("pacienteDetalles", item);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
Almost Done Dude simple mistake cause this issue
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// Clear list here your Activity class list
list.clear()
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Pacientes pacientes = dataSnapshot.getValue(Pacientes.class);
pacientes.setKey(dataSnapshot.getKey());
// One more thing you can do is verify object
if(!list.containes(pacientes)){ // Check if not contains then add
list.add(pacientes);
}
}
// add this method in your adapter and then
adapter.updateList(list)
// No need if you call notifydatasetChanged here if call in above method
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Adapter Update list method
// Sorry for kotlin :-)
fun updateList(it: List<ModelItem>) {
if (it != null) {
list = it
}
notifyDataSetChanged()
}
Try using
notifyItemRemoved(i);
notifyDataSetChanged();
Where i is the index of the item that was removed.

Recycler view duplicates newly added item every time you load the activity again

I am building a chatting app. and in it i have a messaging system powered by firebase. and to load them on the front end I am using recycler view however every time I leave the activity and come back it is still fine but when I add a new message after coming back I duplicates
if that seemed hard to understand here is a video showing what is happening
Recycler View Adapter
public List<Chat> chatList;
public FirebaseAuth mAuth;
public DatabaseReference reference;
public DatabaseReference dbRef;
public String userid;
public MessageAdapter(List<Chat> chat, String userId) {
this.chatList = chat;
this.userid = userId;
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView senderMessage, ReceiverMessage, sender_image_time, receiver_image_time, sender_name, receiver_name, sender_audio_time, receiver_audio_time;
public ImageView messageSenderPicture,messageReceiverPicture;
public CircleImageView receiver_profile_image, sender_profile_image, sender_audio_image, receiver_audio_image;
public SeekBar sender_audio_bar, receiver_audio_bar;
public ImageButton sender_audio_play, receiver_audio_play, sender_audio_pause, receiver_audio_pause;
public ImageView sender_imageView, receiverImageView;
public ConstraintLayout sender_audio_layout, receiver_audio_layout;
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Runnable runnable;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
senderMessage = itemView.findViewById(R.id.senderText);
ReceiverMessage = itemView.findViewById(R.id.receiverText);
messageReceiverPicture = itemView.findViewById(R.id.message_receiver_image_view);
messageSenderPicture = itemView.findViewById(R.id.message_sender_image_view);
sender_image_time = itemView.findViewById(R.id.sender_time_image);
receiver_image_time = itemView.findViewById(R.id.receiver_time_image);
receiver_profile_image = itemView.findViewById(R.id.receiver_profile_image);
sender_profile_image = itemView.findViewById(R.id.sender_profile_image);
sender_name = itemView.findViewById(R.id.sender_name);
receiver_name = itemView.findViewById(R.id.receiver_name);
sender_audio_layout = itemView.findViewById(R.id.sender_audio_layout);
receiver_audio_layout = itemView.findViewById(R.id.receiver_audio_layout);
sender_audio_image = itemView.findViewById(R.id.sender_image_audio);
receiver_audio_image = itemView.findViewById(R.id.receiver_image_audio);
sender_audio_bar = itemView.findViewById(R.id.seekBar);
receiver_audio_bar = itemView.findViewById(R.id.receiver_seekBar);
sender_audio_play = itemView.findViewById(R.id.sender_play);
receiver_audio_play = itemView.findViewById(R.id.receiver_play);
sender_audio_time = itemView.findViewById(R.id.sender_audio_time);
receiver_audio_time = itemView.findViewById(R.id.receiver_audio_time);
sender_imageView = itemView.findViewById(R.id.imageView4);
receiverImageView = itemView.findViewById(R.id.receiver_imageView4);
sender_audio_pause = itemView.findViewById(R.id.sender_pause);
receiver_audio_pause = itemView.findViewById(R.id.receiver_pause);
mediaPlayer = new MediaPlayer();
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_meeage_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, final int position) {
String messageSenderId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
final Chat chat = chatList.get(position);
String fromUserID = chat.getSender();
String userID = chat.getReceiver();
String fromMessageType = chat.getType();
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
dbRef = FirebaseDatabase.getInstance().getReference().child(userID);
holder.senderMessage.setVisibility(View.GONE);
holder.ReceiverMessage.setVisibility(View.GONE);
holder.messageSenderPicture.setVisibility(View.GONE);
holder.messageReceiverPicture.setVisibility(View.GONE);
holder.receiver_image_time.setVisibility(View.GONE);
holder.sender_image_time.setVisibility(View.GONE);
holder.sender_profile_image.setVisibility(View.GONE);
holder.receiver_profile_image.setVisibility(View.GONE);
holder.sender_name.setVisibility(View.GONE);
holder.receiver_name.setVisibility(View.GONE);
holder.sender_audio_layout.setVisibility(View.GONE);
holder.receiver_audio_layout.setVisibility(View.GONE);
if (fromMessageType.equals("text")) {
if (fromUserID.equals(messageSenderId)) {
holder.senderMessage.setVisibility(View.VISIBLE);
holder.senderMessage.setBackgroundResource(R.drawable.sender_layout);
holder.senderMessage.setText(chat.getMessage() + "\n" + " " + chat.getTime());
} else {
holder.senderMessage.setVisibility(View.INVISIBLE);
holder.ReceiverMessage.setVisibility(View.VISIBLE);
holder.ReceiverMessage.setBackgroundResource(R.drawable.receiver_layout);
holder.ReceiverMessage.setText(chat.getMessage() + "\n" + " " + chat.getTime());
}
}else if (fromMessageType.equals("image")) {
if (fromUserID.equals(messageSenderId)) {
holder.messageSenderPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(messageSenderId).child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String name = snapshot.getValue().toString();
holder.sender_name.setText(name);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_name.setVisibility(View.VISIBLE);
ref.child("Users").child(messageSenderId).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.sender_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_profile_image.setVisibility(View.VISIBLE);
Picasso.get().load(chat.getMessage()).into(holder.messageSenderPicture);
holder.sender_image_time.setVisibility(View.VISIBLE);
holder.sender_image_time.setText(chat.getTime());
} else {
holder.messageReceiverPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userid).child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String name = snapshot.getValue().toString();
holder.receiver_name.setText(name);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_name.setVisibility(View.VISIBLE);
ref.child("Users").child(userid).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.receiver_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_profile_image.setVisibility(View.VISIBLE);
Picasso.get().load(chat.getMessage()).into(holder.messageReceiverPicture);
holder.receiver_image_time.setVisibility(View.VISIBLE);
holder.receiver_image_time.setText(chat.getTime());
}
} else if(fromMessageType.equals("audio")) {
if (fromUserID.equals(messageSenderId)) {
holder.sender_audio_layout.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(messageSenderId).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.sender_audio_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_audio_time.setText(chat.getTime());
final MediaPlayer mediaPlayer = new MediaPlayer();
holder.sender_audio_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.sender_audio_play.setVisibility(View.INVISIBLE);
holder.sender_audio_pause.setVisibility(View.VISIBLE);
try {
mediaPlayer.setDataSource(chat.getMessage());
mediaPlayer.prepare();
mediaPlayer.start();
holder.sender_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.sender_audio_play.setVisibility(View.VISIBLE);
holder.sender_audio_pause.setVisibility(View.INVISIBLE);
holder.sender_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
holder.sender_audio_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.sender_audio_play.setVisibility(View.VISIBLE);
holder.sender_audio_pause.setVisibility(View.INVISIBLE);
mediaPlayer.pause();
mediaPlayer.reset();
holder.sender_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
} else {
holder.receiver_audio_layout.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userid).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.receiver_audio_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_audio_time.setText(chat.getTime());
final MediaPlayer mediaPlayer = new MediaPlayer();
holder.receiver_audio_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.receiver_audio_play.setVisibility(View.INVISIBLE);
holder.receiver_audio_pause.setVisibility(View.VISIBLE);
try {
mediaPlayer.setDataSource(chat.getMessage());
mediaPlayer.prepare();
mediaPlayer.start();
holder.receiver_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.receiver_audio_play.setVisibility(View.VISIBLE);
holder.receiver_audio_pause.setVisibility(View.INVISIBLE);
holder.receiver_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
holder.receiver_audio_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.receiver_audio_play.setVisibility(View.VISIBLE);
holder.receiver_audio_pause.setVisibility(View.INVISIBLE);
mediaPlayer.pause();
mediaPlayer.reset();
holder.receiver_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
}
} else {
if (fromUserID.equals(messageSenderId)) {
holder.messageSenderPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(messageSenderId).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.sender_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_profile_image.setVisibility(View.VISIBLE);
holder.messageSenderPicture.setBackgroundResource(R.drawable.file);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(chatList.get(position).getMessage()));
holder.itemView.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(holder.itemView.getContext(), "Your Current Device Doesn't have the application to preview this file", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
} else {
holder.messageReceiverPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userid).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.receiver_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_profile_image.setVisibility(View.VISIBLE);
holder.messageReceiverPicture.setBackgroundResource(R.drawable.file);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(chatList.get(position).getMessage()));
holder.itemView.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(holder.itemView.getContext(), "Your Current Device Doesn't have the application to preview this file", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
}
}
}
#Override
public int getItemCount() {
return chatList.size();
}
}
My Chat Activity
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint("ShowToast")
#Override
protected void onStart() {
super.onStart();
Toast.makeText(SarimPage.this, fUser.getUid(), Toast.LENGTH_SHORT); // Validate Id
Global global = new Global();
global.updateUserStatus("Active Now");
reference.child("Users").child(Objects.requireNonNull(getIntent().getStringExtra("userID"))).child("userState")
.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String status21 = Objects.requireNonNull(snapshot.child("state").getValue()).toString();
String time = Objects.requireNonNull(snapshot.child("time").getValue()).toString();
if (status21.equals("offline")) {
status2.setVisibility(View.VISIBLE);
userStatus.setText("Last Seen " + time);
}
if(status21.equals("online")) {
status2.setVisibility(View.INVISIBLE);
status.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
if(status21.equals("Active Now")){
status2.setVisibility(View.INVISIBLE);
status.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
if(status21.equals("typing...")){
status2.setVisibility(View.INVISIBLE);
status.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
if (status21.equals("away")) {
status3.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference.child("Messages").addChildEventListener(new ChildEventListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Chat chats = snapshot.getValue(Chat.class);
assert chats != null;
if(chats.getReceiver().equals(currentUser) && chats.getSender().equals(userID)
|| chats.getReceiver().equals(userID) && chats.getSender().equals(currentUser)) {
chatList.add(chats);
}
messageAdapter.notifyDataSetChanged();
messageList.smoothScrollToPosition(Objects.requireNonNull(messageList.getAdapter()).getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onUserLeaveHint() {
Global global = new Global();
global.updateUserStatus("offline");
chatList.clear();
super.onUserLeaveHint();
}
#Override
protected void onStop() {
super.onStop();
chatList.clear();
}
#Override
protected void onDestroy() {
super.onDestroy();
chatList.clear();
}
Sorry there is way too much code in this activity so i am only showing methods i think will be usefull such as what i am doing on acitivty start stop or pause.
Chat Model
public class Chat {
private String sender;
private String receiver;
private String message;
private String time;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Chat() {}
public Chat(String sender, String receiver, String message) {
this.message = message;
this.receiver = receiver;
this.sender = sender;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
(Also when i do this i want all the previous chat history to still be displayed)
I'm not really sure if this is the main source of your problems, but it seems like the ChildEventListener you're adding on Messages reference is being called every time the activity is launched or relaunched. This has the effect of adding multiple listener to the Messages reference (multiple time the lates child added to your RecyclerView), what you should do is to maybe move the
reference.child("Messages").addChildEventListener(new ChildEventListener() {...}
inside onCreate or make sure there is only one ChildEventListener listening to your Messages reference when launching your activity.
Hope this will help, have a good day :)
Get same firebase instance when you reopen app.
FirebaseDatabase database;
//always use this getFirebaseDatabase() method when you need database instance.
public FirebaseDatabase getFirebaseDatabase() {
if(database==null){
database=FirebaseDatabase.getInstance();
}
return database;
}

RecyclerView items not Displayed in my MainActivity

I'm building a chat app which have post feature, When I create a post in NewPostActivity, the image and text are uploaded (because I can see them in firebase Database tree) but The problem is nothing is shown in my MainActivity which is supposed to display my posts.
I used Firebase UI for the Rv but I'm not sure is the problem lies in NewPostActivity or the MainActivity.
I tried to run the debugger to see but there is no error or null point exception.
NewPostActivity.java
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting() {
progressDialog=new ProgressDialog(NewPostActivity.this);
progressDialog.setTitle("Uploading Image");
progressDialog.setMessage("Please Wait while we process the image");
progressDialog.setCanceledOnTouchOutside(false);
final String desc_val=mPostDesc.getText().toString().trim();
if(!TextUtils.isEmpty(desc_val) && mImageUri!=null){
progressDialog.show();
String random_name= random();
StorageReference filepath = storageReference.child("Blog_Images").child(random_name);
filepath.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
while (!uriTask.isComplete());
final Uri downloadUrl = uriTask.getResult();
final DatabaseReference newPost = mRootRef.child("Blog").push();
final String user_id= mCurrentUser.getUid();
mRootRef.child("Users").child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("user_id").setValue(user_id);
newPost.child("timestamp").setValue(ServerValue.TIMESTAMP);
newPost.child("username").setValue(dataSnapshot.child("name").getValue());
newPost.child("thumb_image").setValue(dataSnapshot.child("thumb_image").getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
progressDialog.dismiss();
startActivity(new Intent(NewPostActivity.this,MainActivity.class));
finish();
}
});
}
}
MainActivity.java
Query conversationQuery = mDatabase.orderByChild("timestamp");
FirebaseRecyclerOptions<Blog> options = new FirebaseRecyclerOptions.Builder<Blog>()
.setQuery(conversationQuery, Blog.class)
.build();
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(options) {
#NonNull
#Override
public BlogViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_single_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final BlogViewHolder viewHolder, int position, #NonNull final Blog model) {
viewHolder.setContext(getApplicationContext());
final String list_blog_id = getRef(position).getKey();
viewHolder.setLikeBtns(list_blog_id);
Query lastMessageQuery = mDatabase.child(list_blog_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setStatus(model.getStatus());
viewHolder.setPostImage(model.getThumb_image());
viewHolder.setTime(model.getTimestamp());
userID = model.getUid();
}
#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) {
}
});
viewHolder.postImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent imageFullScreen = new Intent(getApplicationContext(), PhotoActivity.class);
imageFullScreen.putExtra("uid", list_blog_id);
imageFullScreen.putExtra("from", "RequestsFragment");
startActivity(imageFullScreen);
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(list_blog_id).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(list_blog_id).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(list_blog_id).child(mAuth.getCurrentUser().getUid()).setValue("Lliked");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
There is some parts of your code that are not shown, also as I don't see a screenshot of your database I don't know if I will give a correct answer, but obviously you need to start listening to the database before you get the data with firebase UI.
So before this:
mBlogList.setAdapter(firebaseRecyclerAdapter);
Add this:
firebaseRecyclerAdapter.startListening();
Refer to this to know more about how to set your firebase UI.

I need to get user image from firebase to show it on ViewHolder after user uplaoded thier image in profile activity

I have a profile activity that user upload their profile images, user uploads 2 images ( back and front) the images are showing fine in the profile activity, but I also want to show one of this image (back or front) in another activity ( ViewHolder activity ). I have tried many things but couldn't figure out as i am only testing how firebase works, I really appreciate if someone can help me here.
Here is my profile activity where user upload images to firebase.
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView backimage;
private CircleImageView profileimage;
TextView totalscore,correctattempts,totalattempts,user_name,java_score,python_score,php_score,android_score,phone_number;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl;
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference("Database_Path");
java_score=findViewById(R.id.javascore);
phone_number=findViewById(R.id.user_phonenumber);
python_score=findViewById(R.id.pythonscore);
php_score=findViewById(R.id.phpscore);
android_score =findViewById(R.id.androidscore);
backimage = findViewById(R.id.header_cover_image);
profileimage=findViewById(R.id.user_profile_photo);
totalattempts=findViewById(R.id.questionsattempted);
correctattempts=findViewById(R.id.correctattempts);
totalscore=findViewById(R.id.totalscore);
user_name =findViewById(R.id.user_profile_name);
backimage.setOnClickListener(this);
profileimage.setOnClickListener(this);
user_name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
user_name.setText(Common.currentUser.getUserName());
phone_number.setText(Common.currentUser.getEmail());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/* String score=dataSnapshot.child(Common.currentuser.getUsername()).child("totalScore").getValue().toString();
totalscore.setText(score);
String tattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("questionsAttempted").getValue().toString();
totalattempts.setText(tattempts);
String cattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("correctAttempts").getValue().toString();
correctattempts.setText(cattempts);
phone_number.setText(Common.currentuser.getEmail());
*/
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtobackimage").getValue().toString())
.into(backimage);
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtoprofileimage").getValue().toString())
.into(profileimage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
scoretbl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Java").exists())
java_score.setText(dataSnapshot.child("Java").child("score").getValue().toString());
if(dataSnapshot.child("Python").exists())
python_score.setText(dataSnapshot.child("Python").child("score").getValue().toString());
if(dataSnapshot.child("PHP").exists())
php_score.setText(dataSnapshot.child("PHP").child("score").getValue().toString());
if(dataSnapshot.child("Android").exists())
android_score.setText(dataSnapshot.child("Android").child("score").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST&&resultCode ==RESULT_OK
&& data !=null && data.getData()!= null){
filepath = data.getData();
if(id==R.id.header_cover_image)
Picasso.with(this).load(filepath).into(backimage);
else
Picasso.with(this).load(filepath).into(profileimage);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.header_cover_image:{
id = R.id.header_cover_image;
chooseImage();
uploadImageback();
break;
}
case R.id.user_profile_photo:{
id = R.id.user_profile_photo;
chooseImage();
uploadImageprofile();
break;
}
}
}
private void uploadImageback() {
final StorageReference backref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"back");
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading..");
progressDialog.show();
backref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
backref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtobackimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void uploadImageprofile() {
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading.. ");
progressDialog.show();
final StorageReference profileref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"profile");
profileref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtoprofileimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Profile Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Profile not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+" %");
}
});
}
}
}
and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name_text,score_text;
private ItemClickListener itemClickListener;
public RankingViewHolder(View itemView) {
super(itemView);
name_text = (TextView) itemView.findViewById(R.id.name_text);
score_text = (TextView) itemView.findViewById(R.id.score_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
and the Fragment activity
public class RankingFragment extends Fragment {
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
//Using orderByChild method , this will sort the ranking in ascending order
//reverse the data by using layout manager
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position) {
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
//prevent crash when user click
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and here is my Ranking class
public class Ranking {
private String userName;
private long score;
private String urlProfilePic;
public Ranking(){
}
public Ranking(String userName, long score, String pathtobackimage ) {
this.userName = userName;
this.score = score;
this.urlProfilePic = pathtobackimage;
}
public String getUrlProfilePic() {
return urlProfilePic;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
Here the screen shot to help more how I wanted
I put my comment in answer field because of this restriction: 'You must have 50 reputation to comment'.
Anyway, back to your question. One solution would be to save the current user 'key' to a SharedPreference file. In your new Activity, use that 'key' to retrieve the data from Firebase.
EDIT: Added solution
Quoted: "...and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity..."
Solution: Search for fixme. In RankingViewHolder class, add:
public class RankingViewHolder extends ...
//...
public TextView name_text, score_text;
public ImageView profileImageView; //fixme
//...
public RankingViewHolder(View itemView) {
//...
score_text = (TextView) itemView.findViewById(R.id.score_text);
profileImageView = (ImageView) itemView.findViewById(R.id.profile_image_view); //fixme
//...
Inside populateViewHolder()
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext()) //fixme
.load(Common.currentUser.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView); //fixme
Inside RankingFragment class, since you are already using Common.currentUser.getUserName(), might as well create another variable under it to store the url link to the user's profile picture, and retrieve the link via Common.currentUser.getUrlProfilePic().
EDIT#2:
The images stored in FB storage have this links:
gs://FIXME_FIREBASE.com/images/userName/userNameback.jpeg
gs://FIXME_FIREBASE.com/images/userName/userNameprofile.jpeg
However to use in Picasso, need this kind of links:
https://firebasestorage.googleapis.com/v0/b/FIXME/o/FIXME/images/userName/userNameback.jpeg?alt=media&token=FIXME
Question is how to get that?
One solution is that after you successfully upload the image, get the download url (example below).
The tricky part is that the download url is not immediately available, and you have to use .getMetadata(), .getDownloadUrl() to do that.
Once the url is received, you have to figure out how to save this link to the user's profile in your FB database.
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageMetadata storageMetadata = taskSnapshot.getMetadata();
StorageReference reference = storageMetadata.getReference();
reference.getDownloadUrl() // Get the download URL for the file
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i(TAG, uri.toString()); //fixme: save this to user's profile
}
});
}
Inside populateViewHolder, you are using Ranking model that contains the username and score.
Modify that Ranking model class to add an additional String variable urlProfilePic that contains the url to the user's image (above result), and generate the getter for it called getUrlProfilePic(). Then you can use it in this way inside the populateViewHolder:
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext())
.load(model.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView);

Firebase Recycler Adapter is not showing my Recyclerview in Fragments

Basically i followed the accepted answer of this with few changes in my Activity and it worked perfect. My problem is that I wrote the exact same codes for my Fragment. when I open my app, it doesn't show anything. Before I changed my code in my fragment from a custom Adapter to the FirebaseRecyclerAdapter, everything worked fine.
This is my Fragment class
public class HomeFragment extends BaseFragment {
public Button buttonsrch, openFreezer, openRef, openPantry, scrollToFreezer, scrollToRef, scrollToPantry;
public NestedScrollView scrollView;
public RelativeLayout mFreezerLayout,mRefrigeratorLayout, mPantryLayout;
public FloatingActionButton mAddItems;
public DatabaseReference mDatabaseFreezer;
public RecyclerView mFreezerRecyclerView;
public ArrayList<Event> mDataSet;
private FirebaseRecyclerAdapter<Event, ProductHolder> firebaseRecyclerAdapter;
#Override
public int getLayoutResId() {
return R.layout.fragment_home;
}
#Override
public View inOnCreateView(View root, #Nullable ViewGroup container, Bundle savedInstancesState) {
View view = mRoot;
buttonsrch = view.findViewById(R.id.searchButton);
openPantry = view.findViewById(R.id.ShowMorePantry);
openRef = view.findViewById(R.id.ShowMoreRefrigerator);
openFreezer = view.findViewById(R.id.ShowMoreFreezer);
scrollToFreezer = view.findViewById(R.id.bringToFreezer);
scrollToPantry = view.findViewById(R.id.bringToPantry);
scrollToRef = view.findViewById(R.id.bringToRefrigerator);
scrollView = view.findViewById(R.id.scrollViewHomeFragment);
mFreezerLayout = view.findViewById(R.id.FreezerLayout);
mPantryLayout =view.findViewById(R.id.PantryRelativeLayout);
mRefrigeratorLayout = view.findViewById(R.id.RefrigeratorRelativeLayout);
mAddItems = view.findViewById(R.id.addItems_Inventory);
mAddItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), AddInventoryActivity.class));
}
});
buttonsrch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), Search_Activity.class);
getActivity().startActivity(i);
}
});
openPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent h = new Intent(getActivity(), PantryActivity.class);
getActivity().startActivity(h);
}
});
openRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent g = new Intent(getActivity(), RefActivity.class);
getActivity().startActivity(g);
}
});
openFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent s = new Intent(getActivity(), FreezerActivity.class);
getActivity().startActivity(s);
}
});
scrollToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToFreezer();
}
});
scrollToRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToRef();
}
});
scrollToPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToPantry();
}
});
mDataSet = new ArrayList<>();
mFreezerRecyclerView = view.findViewById(R.id.FreezerRecyclerView);
mFreezerRecyclerView.setHasFixedSize(true);
mFreezerRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDatabaseFreezer = FirebaseDatabase.getInstance().getReference().child("FreezerItems");
Query query = mDatabaseFreezer;
FirebaseRecyclerOptions<Event> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Event>()
.setQuery(query, Event.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, ProductHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(ProductHolder holder, int position, Event model) {
model = mDataSet.get(position);
holder.mItemName.setText(model.getName());
holder.mItemDate.setText(model.getDate());
final Event finalModel = model;
holder.mDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseFreezer.child(finalModel.get_id()).removeValue();
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_view_row_inventory,parent,false);
return new ProductHolder(view);
}
};
mDatabaseFreezer.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String, String> value = (HashMap<String,String>) dataSnapshot.getValue();
if (value != null) {
String name = value.get("Name");
String date = value.get("Date");
String key = value.get("Key");
mDataSet.add(new Event(name,date,null, key));
Collections.sort(mDataSet, new Comparator<Event>() {
#Override
public int compare(Event event, Event t1) {
if (event.getDate() == null || t1.getDate() == null)
return 0;
return event.getDate().compareTo(t1.getDate());
}
});
}
}
#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) {
}
});
mFreezerRecyclerView.setAdapter(firebaseRecyclerAdapter);
return root;
}
private class ProductHolder extends RecyclerView.ViewHolder{
private TextView mItemName, mItemDate;
private Button mDeleteBtn;
public ProductHolder(View itemView) {
super(itemView);
mItemName = itemView.findViewById(R.id.ItemNameTxtView);
mItemDate = itemView.findViewById(R.id.BestBeoforeTxtView);
mDeleteBtn = itemView.findViewById(R.id.deleteItem);
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null){
firebaseRecyclerAdapter.startListening();
}
}
private void FocusToFreezer(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mFreezerLayout.getTop());
}
});
}
private void FocusToRef(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mRefrigeratorLayout.getTop());
}
});
}
private void FocusToPantry(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mPantryLayout.getTop());
}
});
}
}
The only difference I could find is OnStart() and onStop() in activity are protected while on fragments are public
EDIT I found another page with the same problem and apparently FirebaseRecyclerAdapter doesn't work well with Fragments
I finally found an answer
simply remove mFreezerRecyclerView.setHasFixedSize(true);

Categories

Resources