Failed to Sum up the recyclerview items value - java

I am totally new to Android Studio.
I created recycleview for Budgeting. I created a Budget description and budget value for each item.
I am trying to sum up all the values of the recyclerview. I have tried different methods over the night but failed to do. PLease help!!!
Adapter:
package com.example.personalwallet.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.personalwallet.Model.Budget;
import com.example.personalwallet.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
private ArrayList<Budget> userlist;
private DatabaseReference databaseReference;
private String uId;
int sum=0;
public recyclerAdapter(ArrayList<Budget> userlist,String uId){
this.userlist=userlist;
this.uId = uId;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView nameTxt,amountTXT;
CardView rootCardView;
ImageView deleteSupplierIV;
public MyViewHolder(final View view){
super(view);
nameTxt = view.findViewById(R.id.name);
amountTXT = view.findViewById(R.id.value);
rootCardView = itemView.findViewById(R.id.single_supplier_cardview_id);
deleteSupplierIV = itemView.findViewById(R.id.delete_supplier_IV);
}
}
#NonNull
#Override
public recyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items,parent,false);
return new MyViewHolder(itemview);
}
#Override
public void onBindViewHolder(#NonNull recyclerAdapter.MyViewHolder holder, int position) {
Budget user = userlist.get(position);
String name,amount;
name = user.getBudgetDescription();
amount = user.getAmount();
holder.nameTxt.setText(name);
holder.amountTXT.setText(amount);
if (user.isVisibilityStatus()){
holder.deleteSupplierIV.setVisibility(View.GONE);
}
holder.rootCardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.deleteSupplierIV.setVisibility(View.VISIBLE);
user.setVisibilityStatus(false);
return true;
}
});
holder.deleteSupplierIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSupplier(user.getBudgetDescription());
}
private void deleteSupplier(String supplierName) {
DatabaseReference productReference = databaseReference.child(supplierName);
productReference.removeValue();
userlist.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return userlist.size();
}
}
Activity Code:
package com.example.personalwallet.NavCategories;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.personalwallet.Adapter.recyclerAdapter;
import com.example.personalwallet.AddBudgetActivity;
import com.example.personalwallet.Model.Budget;
import com.example.personalwallet.Prevalent.Prevalent;
import com.example.personalwallet.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Budgets extends AppCompatActivity{
private FloatingActionButton addNewBudgetFAB;
private ArrayList<Budget> userlist;
private RecyclerView recyclerView;
private String uId;
DatabaseReference databaseReference;
recyclerAdapter adapter;
TextView TotalBudgetTv;
public int total_budget =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budgets);
userlist = new ArrayList<Budget>();
recyclerView = findViewById(R.id.suppliers_recyclerViewID);
TotalBudgetTv = findViewById(R.id.TotalBudgetTv);
uId = Prevalent.currentOnlineUser.getPhone();
adapter = new recyclerAdapter(userlist,uId);
setUserInfo();
setAdapter();
**for (int i=0; i<userlist.size(); i++){
total_budget = total_budget+Integer.parseInt(userlist.get(i).getAmount());
}**
TotalBudgetTv.setText("Total Budget: " + Integer.toString(total_budget));
addNewBudgetFAB = findViewById(R.id.addNewSuppliersFABID);
addNewBudgetFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Budgets.this, AddBudgetActivity.class);
startActivity(intent);
}
});
}
private void setAdapter() {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
private void setUserInfo() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userlist.clear();
if (snapshot.exists()) {
for (DataSnapshot data : snapshot.getChildren()) {
Budget supplier = data.getValue(Budget.class);
userlist.add(supplier);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this is my model class:
package com.example.personalwallet.Model;
public class Budget {
private String BudgetDescription;
private String amount;
public boolean isVisibilityStatus() {
return visibilityStatus;
}
public void setVisibilityStatus(boolean visibilityStatus) {
this.visibilityStatus = visibilityStatus;
}
private boolean visibilityStatus = true;
public Budget(){}
public Budget(String budgetDescription, String amount) {
BudgetDescription = budgetDescription;
this.amount = amount;
}
public String getBudgetDescription() {
return BudgetDescription;
}
public void setBudgetDescription(String budgetDescription) {
BudgetDescription = budgetDescription;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}

Try to put your forloop calculation inside onDataChange because in oncreate method your userlist is empty. So when onDataChange called after that new value added to userlist and calculate your total there.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userlist.clear();
if (snapshot.exists()) {
for (DataSnapshot data : snapshot.getChildren()) {
Budget supplier = data.getValue(Budget.class);
userlist.add(supplier);
adapter.notifyDataSetChanged();
}
for (int i=0; i<userlist.size(); i++)
{
total_budget = total_budget+Integer.parseInt(userlist.get(i).getAmount());
}
TotalBudgetTv.setText("Total Budget: " + Integer.toString(total_budget));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

In the adapter's constructor you will get the ArrayList which contains all data. Here, you can run a for loop. which will read each object one by one and add in sum.
public recyclerAdapter(ArrayList<Budget> userlist, String uId){
this.userlist=userlist;
this.uId = uId;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
for(int i = 0; i<userlist.size(); i++){
Budget user = userlist.get(i);
sum = sum + user.getAmount();
}
}

Related

How to get Int value from an Adapter to Activity in android

I want to get an int value from my adapter class to my activity but I am getting nothing while using this code:
Here is my adapter:
package com.capi.ccecommerceapp.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder>
{
private Context context;
private List<Cart> cartList;
private String productImage;
public int overTotalPrice = 0;
public CartAdapter(Context context, List<Cart> cartList ) {
this.context = context;
this.cartList = cartList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.cartName.setText(cartList.get(position).getProductName());
holder.cartPrice.setText(cartList.get(position).getProductPrice());
holder.cart_qty.setText(String.valueOf(cartList.get(position).getProductQuantity()));
int oneTypeProductTPrice = ((Integer.parseInt(cartList.get(position).getProductPrice()))) * cartList.get(position).getProductQuantity();
overTotalPrice = overTotalPrice + oneTypeProductTPrice;
/*FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();*/
/* holder.cartPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty<10)
{
cartQty++;
}
}
});
holder.cartMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty>1)
{
cartQty--;
}
}
});
holder.cart_qty.setText(cartQty);
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cartList.remove(cartList.get(position));
}
});*/
/* holder.wishlistBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.wishlistBtn.getTag().equals("add"))
{
holder.wishlistBtn.setImageResource(R.drawable.ic_love_fill);
holder.wishlistBtn.setTag("added");
}
else
{
holder.wishlistBtn.setImageResource(R.drawable.love);
holder.wishlistBtn.setTag("add");
}
}
});*/
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Products")
.child(cartList.get(position).getProductId())
.child("productImage");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if (snapshot.exists()) {
productImage = snapshot.getValue(String.class);
Glide.with(context).load(productImage).into(holder.cartImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return cartList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView cartImage;
TextView cartName;
TextView cartPrice;
ImageView wishlistBtn;
ImageView deleteBtn;
ImageView cartPlus;
ImageView cartMinus;
TextView cart_qty;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cartImage = itemView.findViewById(R.id.cart_image);
cartName = itemView.findViewById(R.id.cart_name);
cartPrice = itemView.findViewById(R.id.cart_price);
wishlistBtn = itemView.findViewById(R.id.add_to_wishlist);
deleteBtn = itemView.findViewById(R.id.delete_cart);
cartPlus = itemView.findViewById(R.id.cart_add);
cartMinus = itemView.findViewById(R.id.cart_minus);
cart_qty = itemView.findViewById(R.id.cart_quantity);
}
}
}
and here is my activity code where I want to set it in textView:
package com.capi.ccecommerceapp.Fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.capi.ccecommerceapp.Adapter.CartAdapter;
import com.capi.ccecommerceapp.address.ShiptoActivity;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CartFragment extends Fragment
{
private RecyclerView cartRecyclerView;
private List<Cart> cartList;
private CartAdapter cartAdapter;
private Button next;
private FirebaseAuth auth;
private FirebaseUser user;
private TextView subtotal;
private TextView items;
private TextView shipping;
private TextView totalPrice;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
cartRecyclerView = view.findViewById(R.id.cartRecycler);
next = view.findViewById(R.id.checkout_btn);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), ShiptoActivity.class));
}
});
subtotal = view.findViewById(R.id.subtotal_price);
items = view.findViewById(R.id.items);
shipping = view.findViewById(R.id.shipping_price);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
cartRecyclerView.setLayoutManager(layoutManager);
cartList = new ArrayList<>();
cartAdapter = new CartAdapter(getContext(), cartList);
cartRecyclerView.setAdapter(cartAdapter);
loadCart();
return view;
}
private void loadCart()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Cart")
.child(user.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren())
{
Cart cart = dataSnapshot.getValue(Cart.class);
cartList.add(cart);
}
cartAdapter.notifyDataSetChanged();
subtotal.setText("$" + cartAdapter.overTotalPrice);
items.setText("Items("+cartAdapter.getItemCount()+")");
int shippingPrice = (cartAdapter.overTotalPrice / 20);
shipping.setText("$" + shippingPrice);
/*int totalPriceFinal = shippingPrice + cartAdapter.getOverTotalPrice();
totalPrice.setText("$" + totalPriceFinal);*/
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I want to get this int:public int overTotalPrice = 0;
And I am getting it as:subtotal.setText("$"+cartAdapter.overTotalPrice);
Anyone have a solution?
???????????????????????
????????????????????
??????????????????????

Recyclerview not updating after activity restart

So, I'm not sure about the title of this question but here it goes. I have a recyclerview for my chat room. The first time the activity started it has no problem displaying the messages but after pressing the back button back to the main activity showing all chat rooms then click the same chat room again it displays nothing. Then, after sent a message it can display all the messages again. I'm not sure what happened, help, please. Oh, I already tried a few things and browse the internet but because I'm not sure what the keyword is, so I'm quite stuck now
Okay, here is the thing
First main activity, (ignore the other 2 tabs, it's empty)
Main Activity
Then open a chat room
First time open chat room fine
Then press back button, back to MainActivity, then open the same room and no chat displayed
chat room not displaying anything
Then it displays messages again after sending a new messages
new message
I have tried to place notifyDataSetChanged() on various event like onStart, onCreate etc but nothing works;
here is my chat activity
package com.divistant.chat.ui.chat;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.divistant.chat.R;
import com.divistant.signup.UserModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
LinearLayout layout;
ImageView send;
EditText message;
ScrollView scrollView;
DatabaseReference refrence1;
DatabaseReference refrence2;
RecyclerView rv;
List<ChatModel> chats = new ArrayList<>();
ChatActivityAdapter adapter;
FirebaseUser cUser;
UserModel target;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Log.w("EVENT","ON Create");
Intent intent = getIntent();
target = (new Gson()).fromJson(intent.getStringExtra("target"),UserModel.class);
send = (ImageView)findViewById(R.id.sendButton);
message = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
rv = (RecyclerView) findViewById(R.id.main_chat_rv);
cUser = FirebaseAuth.getInstance().getCurrentUser();
adapter = new ChatActivityAdapter(chats);
final LinearLayoutManager manager = new LinearLayoutManager(ChatActivity.this,
LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(manager);
refrence1 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(cUser.getUid() + "_" + target.getUserId());
refrence2 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(target.getUserId() + "_" + cUser.getUid());
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("SEND","send message");
if(message.getText().toString().length() > 0){
ChatModel chat = new ChatModel();
chat.setSender(cUser.getEmail());
chat.setMessage(message.getText().toString());
chat.setReceiver(target.getEmailAddress());
chat.setSenderUid(cUser.getUid());
chat.setReceiverUid(target.getUserId());
chat.setTimestamp((new Date()).getTime());
DatabaseReference ref1 = refrence1.push();
ref1.setValue(chat);
DatabaseReference ref2 = refrence2.push();
ref2.setValue(chat);
message.setText("");
}
}
});
refrence1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
Log.e("[CH]","DATACHANGE " + chats.size());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","CANCEL");
}
});
refrence1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","DB CHANGE");
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Log.e("[CH]","DB REMOVE");
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","Child Moved");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","DB ERROR");
}
});
rv.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
Log.e("[CH]","" + adapter.getItemCount());
}
}
Then, here is my ChatActivityAdapter
package com.divistant.chat.ui.chat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.divistant.chat.R;
import com.google.firebase.auth.FirebaseAuth;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int VIEW_TYPE_ME = 1;
private static final int VIEW_TYPE_OTHER = 2;
List<ChatModel> mChats;
public void setmChats(List<ChatModel> mChats) {
this.mChats = mChats;
}
public ChatActivityAdapter(List<ChatModel> mChats) {
this.mChats = mChats;
Log.e("ADAPTER","CONSTRUCTED " + mChats.size());
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case VIEW_TYPE_ME:
View viewChatMine = layoutInflater.inflate(R.layout.chat_item, parent, false);
viewHolder = new MyChatViewHolder(viewChatMine);
break;
case VIEW_TYPE_OTHER:
View viewChatOther = layoutInflater.inflate(R.layout.chat_item_other, parent, false);
viewHolder = new OtherChatViewHolder(viewChatOther);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
configureMyChatViewHolder((MyChatViewHolder) holder, position);
} else {
configureOtherChatViewHolder((OtherChatViewHolder) holder, position);
}
}
private void configureMyChatViewHolder(final MyChatViewHolder myChatViewHolder, int position) {
ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
myChatViewHolder.senderMsgTime.setText(date);
myChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
private void configureOtherChatViewHolder(final OtherChatViewHolder otherChatViewHolder, int position) {
final ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
otherChatViewHolder.receiverMsgTime.setText(date);
otherChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChats.size();
}
#Override
public int getItemViewType(int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
return VIEW_TYPE_ME;
} else {
return VIEW_TYPE_OTHER;
}
}
private static class MyChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView senderMsgTime;
public MyChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet);
senderMsgTime=(TextView) itemView.findViewById(R.id.senderMsgTime);
}
}
private static class OtherChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView receiverMsgTime;
public OtherChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message_ot);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet_ot);
receiverMsgTime=(TextView) itemView.findViewById(R.id.receiverMsgTime_ot);
}
}
}
Thanks
Thats because you are clearing the list on childevent listener and not adding the new child in list and not passing the list to the adapter.
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
Now change the code by adding the lines
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
in my case i used onResume()
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
Can you put rv.setAdapter(adapter) after rv.setLayoutManager(manager);?
And you verify if the method onDataChange(...) its always called??
You can use the following code in the adapter where you want to refresh recyclerview, for example in #Override public void onBackPressed(){} function. If your chats array changed, you should refresh this adapter.
mAdapter = new ChatActivityAdapter(context, chats.get(chats.size() - 1), chats);
recyclerView.setAdapter(mAdapter);

problem in open another activity from a custom adapter in java

I need to open another activity from a custom adapter, just like a list and then when I click on that, it will take to another activity and get a data from database and show it in the text view,
the problem is in SearchAdapter.java in the context.startActivity(intent);
here's my searchAdapter.java
package Adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
//import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.manualdiagnosiskeperawatan.R;
import com.example.manualdiagnosiskeperawatan.isiDiagnosis;
import java.util.List;
import Model.Daftar;
class SearchViewHolder extends RecyclerView.ViewHolder{
public TextView judul, diagnosis;
public SearchViewHolder(View itemView) {
super(itemView);
judul = itemView.findViewById(R.id.judul);
diagnosis = itemView.findViewById(R.id.textViewIsi);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
{
private Context context;
private List<Daftar> data;
public SearchAdapter(Context context, List<Daftar> data) {
this.context = context;
this.data = data;
}
#Override
public SearchViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, final int position)
{
holder.judul.setText(data.get(position).getJudul());
//open activity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, data.get(position).getDiagnosis(),Toast.LENGTH_SHORT).show();
//this code, isn't working
Intent intent = new Intent(context, isiDiagnosis.class);
intent.putExtra("did",data.get(position).getDid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
and here is my isiDiagnosis.java which will be opened when I clicked the list from the SearchAdapter.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
import Model.Daftar;
public class isiDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
List<Daftar> daftars = new ArrayList<>();
private TextView judul, diagnosis;
private String DID = "judul";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_isi_diagnosis);
DID = getIntent().getStringExtra("judul");
database = new Database(this);
diagnosis = (TextView) findViewById(R.id.textViewIsi);
//init DB
loadData(DID);
}
private void loadData(String did) {
//i don't really know how to code, just see from the youtube, so i made this myself
// database.getDiagnosis();
// String diagnosis = daftars.get(database.getDiagnosis());
// database.getDiagnosis(diagnosis.setText());
}
}
here's my searchDiagnosis.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.ListViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Adapter;
import android.widget.ListView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
public class searchDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
#Override
protected void onStart() {
super.onStart();
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_diagnosis);
//init view
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar =(MaterialSearchBar) findViewById(R.id.search_bar);
//init DB
database = new Database(this);
//Setup search bar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(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) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled) {
// recyclerView.setAdapter(adapter);
//if close Search, just restore default
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//Init adapter default set all result
adapter = new SearchAdapter(this,database.getDaftar());
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDataByJudul(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getJudul();
materialSearchBar.setLastSuggestions(suggestList);
}
}
here's my Daftar.class
package Model;
public class Daftar {
public int id;
public String did, judul, diagnosis;
public Daftar(int id,String did, String judul, String diagnosis) {
this.id = id;
this.did = did;
this.judul = judul;
this.diagnosis = diagnosis;
}
public Daftar() {
}
public int getId() {
return id;
}
public String getDid() {
return did;
}
public void setDid(String did) {
this.did = did;
}
public void setId(int id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
}
Look I don't know what kind of database is this, but I know that you are not receiving the intent extra correctly:
In your isiDiagnosis:
............
//get the did like this
DID = getIntent().getStringExtra("did");
.......
loadData(DID);
//loading the data is up to you according to the database
private void loadData(String did) {.........}

How to retrieve array data from children node in Firebase Realtime Database Java? (Firebase Recycler Adapter)

I knew my question is similar with the other questioners but it was not solved my problem because I am still curious about how to declare the item which is the children of parent node. This is my stucture data on my Firebase:
I've tried to created the classes for my case:
DolanIemClass.java
private String name_tourism;
private String location_tourism;
private String info_tourism;
private String telepon;
private String url_photo;
private String url_photo_collage;
private double lat_location_tourism;
private double lng_location_tourism;
public DolanItemClass() {
//constructor untuk panggilan ke DataSnapshot.getValue
}
public DolanItemClass(String name_tourism, String location_tourism, String info_tourism, String telepon, String url_photo, String url_photo_collage, double lat_location_tourism, double lng_location_tourism) {
this.name_tourism = name_tourism;
this.location_tourism = location_tourism;
this.info_tourism = info_tourism;
this.telepon = telepon;
this.url_photo = url_photo;
this.url_photo_collage = url_photo_collage;
this.lat_location_tourism = lat_location_tourism;
this.lng_location_tourism = lng_location_tourism;
}
public String getUrl_photo_collage() {
return url_photo_collage;
}
public String getName_tourism() {
return name_tourism;
}
public void setName_tourism(String name_tourism) {
this.name_tourism = name_tourism;
}
public String getLocation_tourism() {
return location_tourism;
}
public void setLocation_tourism(String location_tourism) {
this.location_tourism = location_tourism;
}
public String getInfo_tourism() {
return info_tourism;
}
public void setInfo_tourism(String info_tourism) {
this.info_tourism = info_tourism;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
public String getUrl_photo() {
return url_photo;
}
public void setUrl_photo(String url_photo) {
this.url_photo = url_photo;
}
public double getLat_location_tourism() {
return lat_location_tourism;
}
public void setLat_location_tourism(double lat_location_tourism) {
this.lat_location_tourism = lat_location_tourism;
}
public double getLng_location_tourism() {
return lng_location_tourism;
}
public void setLng_location_tourism(double lng_location_tourism) {
this.lng_location_tourism = lng_location_tourism;
}
}
DolanViewHolder.class
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
public class DolanImageViewHolder extends RecyclerView.ViewHolder {
private final ImageView imgDetailData;
public DolanImageViewHolder(#NonNull View itemView) {
super(itemView);
imgDetailData = itemView.findViewById(R.id.img_detail_item_data);
}
public void showImageArray(DolanItemClass dolanItemClass){
Glide.with(itemView.getContext()).load(dolanItemClass.getUrl_photo_collage()).into(imgDetailData);
}
}
And the activity class to show the list
package co.id.roningrum.firebasearrayimage;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class DetailTouristListAct extends AppCompatActivity {
private ImageView imgDetailData;
private TextView tvNamaDetail, tvAlamatDetail, tvDescDetail;
private RecyclerView rvImageDetailCollages;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListener;
private FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder> firebaseRecyclerAdapter;
public static final String EXTRA_WISATA_KEY = "tourist_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_tourist_list);
String touristKey = getIntent().getStringExtra(EXTRA_WISATA_KEY);
if(touristKey == null){
throw new IllegalArgumentException("Must pass Extra");
}
imgDetailData = findViewById(R.id.img_detail_data);
tvNamaDetail = findViewById(R.id.tv_name_detail);
tvAlamatDetail = findViewById(R.id.tv_info_tourism_detail);
tvDescDetail = findViewById(R.id.tv_address_detail);
rvImageDetailCollages = findViewById(R.id.rv_photo_collage);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Tourism").child(touristKey);
rvImageDetailCollages.setLayoutManager(new GridLayoutManager(this, 2));
LoadDetailData();
}
private void ShowCollage() {
Query query = databaseReference.child("url_photo_collage");
FirebaseRecyclerOptions<DolanItemClass> options = new FirebaseRecyclerOptions.Builder<DolanItemClass>()
.setQuery(query, DolanItemClass.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull DolanImageViewHolder dolanImageViewHolder, int i, #NonNull DolanItemClass dolanItemClass) {
dolanImageViewHolder.showImageArray(dolanItemClass);
}
#NonNull
#Override
public DolanImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DolanImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_data, parent, false));
}
};
firebaseRecyclerAdapter.notifyDataSetChanged();
rvImageDetailCollages.setAdapter(firebaseRecyclerAdapter);
}
private void LoadDetailData() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DolanItemClass dolanItemClass = dataSnapshot.getValue(DolanItemClass.class);
tvNamaDetail.setText(dolanItemClass.getName_tourism());
tvAlamatDetail.setText(dolanItemClass.getLocation_tourism());
tvDescDetail.setText(dolanItemClass.getInfo_tourism());
Glide.with(getApplicationContext()).load(dolanItemClass.getUrl_photo()).into(imgDetailData);
ShowCollage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(eventListener);
valueEventListener = eventListener;
}
#Override
protected void onStart() {
super.onStart();
LoadDetailData();
if(firebaseRecyclerAdapter!=null){
firebaseRecyclerAdapter.startListening();
}
}
#Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListener);
}
}
I expected that I can show the array of url_photo_collage node but I don't have any idea for my item class.
The problem in your code is that your url_photo_collage field is declared in your DolanItemClass class of type String while in your database is an array. To solve this, change the type of your field from String to a List<String> and get it accordingly in your adapter.

How can I get the key of an item populated from firebase database clicked in the recyclerview

I have a very serious problem. I am using a RecyclerView to populate data(a list of users) from Firebase into my application. Now the problem is that how to reference their respective userIds when a user clicks any of them so it can be used to set the title of the activity's action bar that will be opened. I tried using the getRef() method but it could not be resolved. Below is my code.
My StudentsList
package com.dreamlazerstudios.gtuconline;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import static android.content.ContentValues.TAG;
public class StudentsList extends AppCompatActivity {
DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<Students> listData;
RecyclerView recyclerView;
StudentsList.MyAdapter adapter;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private FirebaseDatabase mFirebaseDatabase;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_students_list);
setTitle("List of Students");
recyclerView = findViewById(R.id.students_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
listData = new ArrayList<>();
adapter = new StudentsList.MyAdapter(listData);
adapter.setHasStableIds(true);
GetDataFirebase();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
void GetDataFirebase() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("Students");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Students students = dataSnapshot.getValue(Students.class);
listData.add(students);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#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) {
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
List<Students> list;
public MyAdapter(List<Students> List) {
this.list = List;
}
#Override
public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
Students students = list.get(position);
String list_user_id = getRef(position).getKey();
holder.news_topic.setText(students.getName());
holder.news_body.setText(students.getProgramme());
if (students.getOnline() == true) {
holder.online.setVisibility(View.VISIBLE);
} else {
holder.online.setVisibility(View.INVISIBLE);
}
Picasso.with(holder.news_image.getContext()).load(students.getThumb_image()).placeholder(R.drawable.student_icon_17870).into(holder.news_image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chat_intent = new Intent(StudentsList.this, ChatActivity.class);
chat_intent.putExtra("user_id", list_user_id );
startActivity(chat_intent);
}
});
}
#NonNull
#Override
public StudentsList.MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_layout, parent, false);
return new StudentsList.MyAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView news_topic, news_body;
CircleImageView news_image;
ImageView online;
public ViewHolder(View itemView) {
super(itemView);
news_topic = itemView.findViewById(R.id.user_single_name);
news_body = itemView.findViewById(R.id.user_single_status);
news_image = itemView.findViewById(R.id.user_single_image);
online = itemView.findViewById(R.id.online_status_icon);
}
}
#Override
public int getItemCount() {
return list.size();
}
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
My model class
package com.dreamlazerstudios.gtuconline;
/**
* Created by Gabriel Hagan on 16/05/2018 at 23:10.
*/
public class Students {
String name;
String programme;
String thumb_image;
Boolean online;
public Boolean getOnline() {
return online;
}
public void setOnline(Boolean online) {
this.online = online;
}
public Students() {
}
public Students(String name, String programme, String thumb_image, Boolean online) {
this.name = name;
this.programme = programme;
this.thumb_image = thumb_image;
this.online = online;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProgramme() {
return programme;
}
public void setProgramme(String programme) {
this.programme = programme;
}
public String getThumb_image() {
return thumb_image;
}
public void setThumb_image(String thumb_image) {
this.thumb_image = thumb_image;
}
}
My ChatActivity
package com.dreamlazerstudios.gtuconline;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ChatActivity extends AppCompatActivity {
private DatabaseReference rootRef;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;
private String mChatUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mChatUser = getIntent().getStringExtra("user_id");
rootRef.child("Users").child("Students").child(mChatUser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String chat_user_name = dataSnapshot.child("name").getValue().toString();
setTitle(chat_user_name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
rootRef.child("Chat").child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
My database snapshot
You can get the key from the DataSnapshot you are getting in onChildAdded. Instead of having a list of students in your adapter, you could keep the list of DataSnapshots. Then you could do something like this:
In StudentsList, change:
List<Students> listData;
To:
List<DataSnapshot> listData;
Also, change onChildAdded:
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
listData.add(dataSnapshot);
//Should probably move these since they don't need to get called for every item.
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
Then in your adapter:
public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
List<DataSnapshot> list;
public MyAdapter(List<DataSnapshot> List) {
this.list = List;
}
#Override
public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
DataSnapshot studentSnapshot = list.get(position);
String list_user_id = studentSnapshot.getKey();
Students students = studentSnapshot.getValue(Students.class)
//The rest unchanged
Inside onBindViewHolder method you can get the key of the user that you are looking for using the following line of code:
String list_user_id = getItem(position);
getRef() is used to obtain a reference to the source location for the snapshot. So you can only use this method on a snapshot object. It returns a DatabaseReference and takes no argument. Below an example:
DatabaseReference ref = dataSnapshot.child("users").getRef();

Categories