I am using Firebase Recycler Adapter in my app to display items from my database, but I want a situation whereby newer items will be at the top of the fragment so i tried to use orderByChild() like this:
Query conversationQuery = mConvDatabase.orderByChild("timestamp");
but that didn't solve the problem.
What i really want to do is to update chat fragment anytime a user receives a new message to move the new conversation to the top just like every other messenger app.
this is my ChatFragment
#Override
public void onStart() {
super.onStart();
Query conversationQuery = mConvDatabase.orderByChild("timestamp");
FirebaseRecyclerAdapter<Conv, ConvViewHolder> firebaseConvAdapter = new FirebaseRecyclerAdapter<Conv, ConvViewHolder>(
Conv.class,
R.layout.users_layout,
ConvViewHolder.class,
conversationQuery
) {
#Override
protected void populateViewHolder(final ConvViewHolder convViewHolder, final Conv conv, int i) {
final String list_user_id = getRef(i).getKey();
// Query MessageQuery = mMessageDatabase.child(list_user_id);
Query lastMessageQuery = mMessageDatabase.child(list_user_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String data = dataSnapshot.child("message").getValue().toString();
String type_image = dataSnapshot.child("type").getValue().toString();
boolean seen = Boolean.parseBoolean(dataSnapshot.getKey());
if (type_image.equals("image")){
convViewHolder.setMessage("image",conv.isSeen());
}else {
convViewHolder.setMessage(data, conv.isSeen());
}}
#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) {
}
});
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();
convViewHolder.setUserOnline(userOnline, getActivity());
}
mConvList.scrollToPosition(0);
convViewHolder.setName(userName);
convViewHolder.setUserImage(userThumb, getContext());
convViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mConvList.setAdapter(firebaseConvAdapter);
firebaseConvAdapter.notifyDataSetChanged();
}
Is there a way i can manipulate the time stamp sent to database so it can be later retrieved in an appropriate manner? or can i just change the arrangement locally in my code as data is been loaded?
You can do something like this.
//Display
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
firebaseRecyclerAdapter.notifyDataSetChanged();
Related
This is my product showing function. When I access this activity from another, the other activity gets destroyed maybe because of memory leaks. How do I fix this issue? How do I close the listeners? I want to destroy this is OnDestroy method because it might be causing a memory leak and also I've read that it's a good practice to do so.
private void getProductDetails(String productID) {
DatabaseReference productsRef = FirebaseDatabase.getInstance().getReference().child("Products");
productsRef.child(productID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Products products = dataSnapshot.getValue(Products.class);
productName.setText(products.getPname());
productPrice.setText(products.getPrice());
if (products.getInStock().equals("Yes")){
inStock.setText("In Stock");
inStock.setTextColor(ContextCompat.getColor(ProductDetailsActivity.this,R.color.primary));
}else {
inStock.setText("Not In Stock");
inStock.setTextColor(ContextCompat.getColor(ProductDetailsActivity.this,R.color.red));
addToCartBtn.setEnabled(false);
}
ifFreeDelivery = "No";
DatabaseReference mref;
final String[] phone = new String[1];
mref = FirebaseDatabase.getInstance().getReference("Values").child("deliveryCharge");
mref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
phone[0] = dataSnapshot.getValue(String.class);
deliveryCharge = Integer.parseInt(phone[0]);
//do what you want with the likes
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Products productsImg = dataSnapshot.getValue(Products.class);
ArrayList<String> test = productsImg.getImage();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference myRef = rootRef.child("Products").child(products.getPid()).child("image");
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//this will be called for every child in your list
test.add(s);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//this will be called for every child changed in your list
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
ArrayList<SlideModel> images = new ArrayList<>();
for(int i = 0; i < test.size() ; i++) {
images.add(new SlideModel(test.get(i),null));
}
productImage.setImageList(images);
productImgDownloadBtn.setOnClickListener(v -> {
for(int i = 0; i < products.getPicCount() ; i++) {
String url = test.get(i).replace(" ","");
DownloadImage(url);
}
});
productDescription.setText(products.getDescription());
productDetailsCopyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Product description",products.getDescription());
clipboard.setPrimaryClip(clip);
Toast.makeText(ProductDetailsActivity.this, "Product description copied..", Toast.LENGTH_SHORT).show();
}
});
//Picasso.get().load(products.getImage().get(0)).into(productImage);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError databaseError) {
}
});
}
As I see in your code, you are using in the first part addValueEventListener(), which means that you are listening for real-time updates. That kind of listener should be removed according to the life cycle of your activity. Please also note, that the onDestroy is not always called.
However, when using addListenerForSingleValueEvent(), there is no need to remove any listener, because it only reads the data once.
Hi I have switch button (switchTaskFinished) on my recycler view,when I am clicking any button, the last button is getting selected. Also when I press button it updates the data to firebase. And changes the button status accordingly. But even though buttons value is true it only updates last button status not others.
public class MyAdaptorUser extends RecyclerView.Adapter<MyAdaptorUser.myViewHolder> {
private Context context;
private ArrayList<TaskModel> taskLists;
private Switch switchTaskFinished;
private OnTaskClickListner mTaskListner;
private AlertDialog dialog;
private AlertDialog.Builder builder;
private TaskConfirmationSender taskConfirmationSender;
public MyAdaptorUser(Context c, ArrayList<TaskModel> t, OnTaskClickListner onTaskClickListner) {
context = c;
taskLists = t;
this.mTaskListner = onTaskClickListner;
}
#NonNull
#Override
public MyAdaptorUser.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
builder = new AlertDialog.Builder(parent.getContext());
builder.setTitle("Please Wait").setView(R.layout.my_progress_view).setCancelable(false);
dialog = builder.create();
return new MyAdaptorUser.myViewHolder(LayoutInflater.from(context).inflate(R.layout.task_preview, parent, false), mTaskListner);
}
#Override
public void onBindViewHolder(#NonNull MyAdaptorUser.myViewHolder holder, final int position) {
//Set title and description to task preview textviews
holder.title.setText(taskLists.get(position).getTaskTitle());
holder.dueDate.setText(taskLists.get(position).getDueDate());
holder.description.setText(taskLists.get(position).getTaskDescription());
//Sets the path of database to taskAwatingConfirmation/task_title/UserEmail
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
try {
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email = removeSpecialCharacter(email);
final DatabaseReference taskConfirmationRef = dbRef
.child("taskAwatingConfirmation")
.child(taskLists.get(position).getTaskTitle())
.child(email);
taskConfirmationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Fetching switchButton Status (Task finished) from database
switchTaskFinished.setChecked(false);
String buttonStatus = (String) dataSnapshot.child("buttonStatus").getValue();
if (buttonStatus != null) {
Log.d("taskerror", buttonStatus);
if (buttonStatus.equals("true")) {
switchTaskFinished.setChecked(true);
} else if (buttonStatus.equals("false")) {
switchTaskFinished.setChecked(false);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
switchTaskFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
//dialog = builder.show();
taskConfirmationSender = new TaskConfirmationSender();
//When Task Finished button is clicked send data to database
sendConfirmationToAdmin(new FirebaseCallBack() {
#Override
public void Callback(TaskConfirmationSender taskConfirmationSender) {
taskConfirmationSender.setButtonStatus(String.valueOf(buttonView.isChecked()));
taskConfirmationSender.setTaskDueDate(taskLists.get(position).getDueDate());
if (buttonView.isChecked()) {
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}
}
});
}
});
} catch (NullPointerException ignored) {
dialog.dismiss();
}
}
private String removeSpecialCharacter(String email) {
StringBuffer sbf = new StringBuffer(email);
email = String.valueOf(sbf.reverse());
int length = email.length();
email = email.substring(4, length);
StringBuffer stringBuffer = new StringBuffer(email);
email = String.valueOf(stringBuffer.reverse());
return email.replace("#", "_");
}
private void sendConfirmationToAdmin(final FirebaseCallBack firebaseCallBack) {
DatabaseReference volunteerRef = FirebaseDatabase.getInstance().getReference()
.child("Volunteer").child("Member")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
taskConfirmationSender = new TaskConfirmationSender();
try {
//Fetching details of users (full name, email) from database and setting their value to taskConfirmation Object
volunteerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("fullName").getValue().toString();
String userEmail = dataSnapshot.child("email").getValue().toString();
String userId = dataSnapshot.getKey();
//TODO: Fetch UID of user and set it to taskConfirmation OBject
taskConfirmationSender.setUserEmail(userEmail);
taskConfirmationSender.setUserName(userName);
taskConfirmationSender.setId(userId);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String submissionDate = day + "/" + month + "/" + year;
taskConfirmationSender.setSubmissionDate(submissionDate);
firebaseCallBack.Callback(taskConfirmationSender);
/**/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (NullPointerException ee) {
}
}
private interface FirebaseCallBack {
void Callback(TaskConfirmationSender taskConfirmationSender);
}
#Override
public int getItemCount() {
return taskLists.size();
}
class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, dueDate, description;
OnTaskClickListner onTaskClickListner;
public myViewHolder(#NonNull View itemView, OnTaskClickListner onTaskClickListner) {
super(itemView);
title = itemView.findViewById(R.id.taskTitle);
dueDate = itemView.findViewById(R.id.taskDueDate);
description = itemView.findViewById(R.id.taskDescription);
switchTaskFinished = itemView.findViewById(R.id.switchTaskFinished);
this.onTaskClickListner = onTaskClickListner;
ConstraintLayout taskBar = itemView.findViewById(R.id.linearLayoutTaskBar);
itemView.setOnClickListener(this);
//hides delete task button
taskBar.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
onTaskClickListner.onTaskClick(getAdapterPosition());
}
}
public interface OnTaskClickListner {
void onTaskClick(int position);
}
}
Maybe its because of the valueEventListener that stays attached:
Instead of this:
taskConfirmationRef.addValueEventListener(new ValueEventListener() {.........
Do this:
taskConfirmationRef.addListenerForSingleValueEvent(new ValueEventListener() {......
And set the switch to checked or unchecked when you turn on or off:
if (buttonView.isChecked()) {
//here
switchTaskFinished.setChecked(true);
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
//here
switchTaskFinished.setChecked(false);
...................
I've just recently started to learn some coding, a little python and java.
I'm trying to make a whatsapp clone as a test, and I've hit a wall.
Basically I have a UID showing as the name of a group chat, and I want to swap it for a groupId I have saved in firebase at the same level as the Uid.
FirebaseDatabase.getInstance().getReference().child("chat").child(chatId).child("info").child("groupId)
I've been following simcoder youtube video and there's a lot of checks and balances happening between user and chat UIDs and I'm getting lost in the middle of all that.
I've tried adding groupId to the adapter and the chatObject, and I can see the data in debug, but I just can't get it to populate the recycler view. I've had a search of the forums here, but can't quite get it to work.
I'm hoping someone can help me out, many thanks
private RecyclerView mChatList;
private RecyclerView.Adapter mChatListAdapter;
private RecyclerView.LayoutManager mChatListLayoutManager;
ArrayList<ChatObject> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
OneSignal.startInit(this).init();
OneSignal.setSubscription(true);
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
#Override
public void idsAvailable(String userId, String registrationId) {
FirebaseDatabase.getInstance().getReference().child("user").child(FirebaseAuth.getInstance().getUid()).child("notificationKey").setValue(userId);
}
});
OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
Button mLogout = findViewById(R.id.logout);
Button mFindUser = findViewById(R.id.finduser);
mFindUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), FindUserActivity.class));
}
});
mLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OneSignal.setSubscription(false);
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return;
}
});
getPermissions();
initializeRecyclerView();
getUserChatList();
}
private void getUserChatList(){
DatabaseReference mUserChatDB = FirebaseDatabase.getInstance().getReference().child("user").child(FirebaseAuth.getInstance().getUid()).child("chat");
mUserChatDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
ChatObject mChat = new ChatObject(childSnapshot.getKey());
boolean exists = false;
for (ChatObject mChatIterator : chatList){
if(mChatIterator.getChatId().equals(mChat.getChatId()))
exists = true;
}
if (exists)
continue;
chatList.add(mChat);
getChatData(mChat.getChatId());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getChatData(String chatId) {
DatabaseReference mChatDB = FirebaseDatabase.getInstance().getReference().child("chat").child(chatId).child("info");
mChatDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String chatId = "";
if(dataSnapshot.child("id").getValue() != null)
chatId = dataSnapshot.child("id").getValue().toString();
for(DataSnapshot userSnapshot : dataSnapshot.child("users").getChildren()){
for(ChatObject mChat : chatList)
if(mChat.getChatId().equals(chatId)){
UserObject mUser = new UserObject(userSnapshot.getKey());
mChat.addUserToArrayList(mUser);
getUserData(mUser);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getUserData(UserObject mUser) {
DatabaseReference mUserDb = FirebaseDatabase.getInstance().getReference().child("user").child(mUser.getUid());
mUserDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserObject mUser = new UserObject(dataSnapshot.getKey());
if(dataSnapshot.child("notificationKey").getValue() != null)
mUser.setNotificationKey(dataSnapshot.child("notificationKey").getValue().toString());
for(ChatObject mChat : chatList)
for(UserObject mUserIt : mChat.getUserObjectArrayList()){
if(mUserIt.getUid().equals(mUser.getUid())){
mUserIt.setNotificationKey(mUser.getNotificationKey());
}
}
mChatListAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void initializeRecyclerView() {
chatList = new ArrayList<>();
mChatList = findViewById(R.id.chatList);
mChatList.setNestedScrollingEnabled(false);
mChatList.setHasFixedSize(false);
mChatListLayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL,false);
mChatList.setLayoutManager(mChatListLayoutManager);
mChatListAdapter = new ChatListAdapter(chatList);
mChatList.setAdapter(mChatListAdapter);
}
From what I see you are passing to the adapter an empty list so that's why there's not data to be displayed.
And also, where you are using mChatListAdapter.notifyDataSetChanged();, you don't set before a populated list to the adapter.
I'm not sure which is the data you want to display but you have to collect in a list from the firebase all the information you want to display, for example, if UserObject is what you want, you have to make an ArrayList<UserObject>, to add there all the objects, pass it to the adapter and then call adapter.notifyDataSetChanged() .
You can make function in the adapter, like :
public void setData(ArrayList<YourObject> list){
yourAdapterList = list
this.notifyDataSetChanged()
}
And then call it from your activity/fragment like adapter.setData( /* your populated list */)
My code is as below... I am new to this line so any help is appreciated.
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options = new FirebaseRecyclerOptions.Builder<Contacts>().setQuery(ChatsRef, Contacts.class).build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull Contacts model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
}
else {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
// i am having trouble from this portion onwards
final String[] retLastMessage = {null};
final String[] retLastMessageTime = {null};
final String[] retLastMessageDate = {null};
RootRef.child("Contacts").child(currentUserID).child(usersIDs).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("LastMessage")) {
retLastMessage[0] = dataSnapshot.child("LastMessage").getValue().toString();
retLastMessageTime[0] = dataSnapshot.child("LastMessageTime").getValue().toString();
retLastMessageDate[0] = dataSnapshot.child("LastMessageDate").getValue().toString();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.userLastMessage.setText(retLastMessage[0]);
String retLastMessageTimeDate = retLastMessageTime[0] + " " + retLastMessageDate[0];
holder.userLastMsgTime.setVisibility(View.VISIBLE);
holder.userLastMsgTime.setText(retLastMessageTimeDate);
//upto this I guess
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
app is crashing when it tries to retrieve these data from firebase
please help. I am using the above code to actually get the final message and time of last message to display it in chats fragment of my app. the last message and last message time are saved in contacts node
this is how the database entry looks like
So you need to do that :
DatabaseReference reference =
FirebaseDatabase.getInstance().getReference("Contacts").child("2").child("3");
// of course you are not going to use 2 and 3 as a child but it's just to illustrate my point
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
after changing the code a little the app ran smoothly
the changed code is:
final String[] retLastMessage = {null};
final String[] retLastMessageTime = {null};
final String[] retLastMessageDate = {null};
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Contacts").child(currentUserID).child(usersIDs);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("LastMessage")) {
retLastMessage[0] = dataSnapshot.child("LastMessage").getValue().toString();
retLastMessageTime[0] = dataSnapshot.child("LastMessageTime").getValue().toString();
retLastMessageDate[0] = dataSnapshot.child("LastMessageDate").getValue().toString();
holder.userLastMessage.setVisibility(View.VISIBLE);
holder.userLastMessage.setText(retLastMessage[0]);
String retLastMessageTimeDate = retLastMessageTime[0] + " " + retLastMessageDate[0];
holder.userLastMsgTime.setVisibility(View.VISIBLE);
holder.userLastMsgTime.setText(retLastMessageTimeDate);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
rest of the code remains same. the problem was i was assigning values after the ValueEventListener. i don't know the proper reason but aster assigning the values inside the ValueEventLister the code seems to run fine.
I am new to firebase and I am in love with this real-time database thing.
However, I am not sure how to display nested data in a recycled view.
Following is my database structure :-
I want to display the data at 0,1,2...The data consist of information about different books.
This is what I have tried so far:-
private void getSelectedBooks() {
FirebaseRecyclerAdapter<BooksInfo, BooksViewHolder> adapter = new FirebaseRecyclerAdapter<BooksInfo, BooksViewHolder>(
BooksInfo.class,
R.layout.book_list,
BooksViewHolder.class,
nextOrder.child(String.valueOf(index))
) {
#Override
protected void populateViewHolder(BooksViewHolder viewHolder, final BooksInfo model, final int position) {
Log.d("BOOKDETAILS",model.getTitle());
// viewHolder.setTitle(model.getTitle());
// viewHolder.setISBN(model.getISBN());
// viewHolder.setDiscount(model.get());
// viewHolder.setQty(model.getQuantity());
// viewHolder.setPrice(model.getPrice());
// viewHolder.setGrossValue(model.get);
// viewHolder.setNetValue(model.get);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference ref = getRef(position);
String key = ref.getKey();
Toast.makeText(AddOrderActivity.this, key, Toast.LENGTH_SHORT).show();
// getRetailerInfo(key);
}
});
}
};
selectedBookRecyclerView.setAdapter(adapter);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(String.valueOf(index)).exists()) {
// run some code
// DisableProgress();
} else {
// DisableProgress();
// Toast.makeText(RetailerActivity.this, "No retailers to display", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Here DatabaseReference nextOrder = mDatabase.child(userId).child("order_details").child(String.valueOf(index));
Any help or suggestion is appreciated.Thank you.