I have a recyclerview where I list expenses' category from Firebase using JAVA, I am looking to group categories so I only get 1 recyclerview item called FOOD, ENTERTAINMENT etc, this and the total amount for every item in that category.
this is my recyclerview result now;
this is my adapter class;
public class CategoriesAdapter extends RecyclerView.Adapter<CategoriesAdapter.ViewHolder> {
private Context mContext;
private ArrayList<Expense> categories;
public CategoriesAdapter(Context mContext, ArrayList<Expense> categories) {
this.mContext = mContext;
this.categories = categories;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.categories_retrieve_layout, parent, false);
return new ViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Expense expense = categories.get(position);
holder.category.setText("" + expense.getCategory());
holder.amount.setText("$ " + formatNumberCurrency(String.valueOf(expense.getAmount())));
}
#Override
public int getItemCount() {
return categories.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView category;
private TextView amount;
private TextView percentage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
category = itemView.findViewById(R.id.category_name);
amount = itemView.findViewById(R.id.category_total_amount);
percentage = itemView.findViewById(R.id.percentage_indicator);
}
}
private static String formatNumberCurrency(String amount) {
DecimalFormat formatter = new DecimalFormat("###,###,###");
return formatter.format(Double.parseDouble(amount));
}
}
and here is how I am reading my data
final Calendar c = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String date = dateFormat.format(c.getTime());
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(Objects.requireNonNull(mAuth.getCurrentUser()).getUid());
Query query = databaseReference.orderByChild("date").equalTo(date);
query.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
expenses.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Expense expense = dataSnapshot.getValue(Expense.class);
expenses.add(expense);
}
categoriesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Here, the output I am expecting to get
any advice on how to create the logic for this?
This is the error I got while trying to use Sambhav. K's answer:
You can check if a value already exists or not when adding it to the list. Try this:
query.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
expenses.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Expense expense = dataSnapshot.getValue(Expense.class);
boolean exists = false;
int count = 0;
for(int i = 0; i < expenses.size(); i++){
count = i;
exists = expenses.get(i).getCategory().equalsIgnoreCase(expense.getCategory());
if(exists) break;
}
if(exists){
expenses.get(count).setAmount(expenses.get(i).getAmount()() + expense.getAmount());
}else{
expenses.add(expense);
}
}
categoriesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
error.printStackTrace();
}
});
Related
I am creating an application and I need to use a nested FirebaseRecyclerAdapter. But I can't find examples on the Internet of how to do it correctly, maybe someone can show with an example how to do it correctly.
Here is my main adapter inside which I need to implement the second adapter:
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<DataSnapshot>()
.setLifecycleOwner((LifecycleOwner)mContext)
.setQuery(FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments"), new SnapshotParser<DataSnapshot>() {
#NonNull
#Override
public DataSnapshot parseSnapshot(#NonNull DataSnapshot snapshot) {
return snapshot;
}
}).build();
adapter = new FirebaseRecyclerAdapter<DataSnapshot, CommentAdapter>(options)
{
#NonNull
#Override
public CommentAdapter onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.comments, parent, false);
return new CommentAdapter(view);
}
#Override
protected void onBindViewHolder(#NonNull CommentAdapter holder, int position, #NonNull DataSnapshot model) {
String comment = model.child("comment").getValue(String.class);
Long dateLong = Long.parseLong(model.child("time").getValue(String.class));
commentID = model.child("commentId").getValue(String.class);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyy HH:mm");
Date date = new Date(dateLong);
Query query = postsReference.orderByKey().equalTo(postId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren())
{
String image = dataSnapshot.child("avatarUri").getValue(String.class);
String nickname = dataSnapshot.child("nickname").getValue(String.class);
Picasso.get().load(image).into(holder.avatar);
holder.nick.setText(nickname);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.comment.setText(comment);
holder.date.setText(simpleDateFormat.format(date));
holder.reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeComment.setText("#" + holder.nick.getText()+" ");
replyLayout.setVisibility(View.VISIBLE);
replyLayout.setBackgroundColor(Color.parseColor("#FF262726"));
replyTo.setText("Replying to " + holder.nick.getText());
}
});
replyLinearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
holder.mRecyclerView.setLayoutManager(replyLinearLayoutManager);
holder.mRecyclerView.setHasFixedSize(true);
FirebaseRecyclerAdapter replyAdapter = setReplyAdapter();
holder.mRecyclerView.setAdapter(replyAdapter);
replyAdapter.startListening();
}
};
Reply class:
public class Reply {
private String userId;
private String comment;
private String date;
private String commentId;
public Reply()
{
}
public Reply(String userId, String comment, String date, String commentId)
{
this.comment = comment;
this.userId = userId;
this.date = date;
this.commentId = commentId;
}
public String getCommentId() {
return commentId;
}
public void setCommentId(String commentId) {
this.commentId = commentId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReplyRecyclerViewAdapter:
public class ReplyRecyclerViewAdapter extends RecyclerView.ViewHolder{
CircleImageView avatar;
TextView nick, comment, date, reply;
public ReplyRecyclerViewAdapter(#NonNull View view) {
super(view);
avatar = view.findViewById(R.id.commentator_avatar_reply);
nick = view.findViewById(R.id.commentator_nick_reply);
comment = view.findViewById(R.id.comment_text_reply);
date = view.findViewById(R.id.reply_date);
reply = view.findViewById(R.id.reply);
}
}
And this is the method in which I call the nested adapter initialization, but I have a problem that when I try to call a variable of this class from holder, the variable does not see them. I marked these fields with comments in the code.
private FirebaseRecyclerAdapter setReplyAdapter()
{
FirebaseRecyclerOptions optionsReply = new FirebaseRecyclerOptions.Builder<DataSnapshot>()
.setLifecycleOwner((LifecycleOwner)mContext)
.setQuery(FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments").child(commentID).child("Reply"), new SnapshotParser<DataSnapshot>() {
#NonNull
#Override
public DataSnapshot parseSnapshot(#NonNull DataSnapshot snapshot) {
return snapshot;
}
}).build();
FirebaseRecyclerAdapter replyAdapter = new FirebaseRecyclerAdapter<DataSnapshot, ReplyRecyclerViewAdapter>(optionsReply)
{
#NonNull
#Override
public ReplyRecyclerViewAdapter onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.comments, parent, false);
return new ReplyRecyclerViewAdapter(view);
}
#Override
protected void onBindViewHolder(#NonNull ReplyRecyclerViewAdapter holder, int position, #NonNull DataSnapshot model) {
String comment = model.child("comment").getValue(String.class);
Long dateLong = Long.parseLong(model.child("time").getValue(String.class));
commentID = model.child("commentId").getValue(String.class);
replyReference = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments").child(commentID).child("Reply");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyy HH:mm");
Date date = new Date(dateLong);
Query query = postsReference.orderByKey().equalTo(postId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren())
{
String image = dataSnapshot.child("avatarUri").getValue(String.class);
String nickname = dataSnapshot.child("nickname").getValue(String.class);
Picasso.get().load(image).into(holder.avatar); //holder.avatar it cannot find avatar variable
holder.nick.setText(nickname); //the same is here
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.comment.setText(comment); //here
holder.date.setText(simpleDateFormat.format(date)); //here
}
};
return replyAdapter;
}
I want to get the value of cost and product name from the date child for all products. I am getting null value for above code.
How to get the value from different Childs?
My Java Class:
public class CompleteExpenses {
String product;
String date;
Long cost;
Long quantity;
public CompleteExpenses() {
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Long getCost() {
return cost;
}
public void setCost(Long cost) {
this.cost = cost;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
}
My adapter:
public class Product_Adapter extends RecyclerView.Adapter {
List<CompleteExpenses> completeExpensesList;
public Product_Adapter(List<CompleteExpenses> completeExpensesList) {
this.completeExpensesList = completeExpensesList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_layout,parent,false);
ViewHolderClass viewHolderClass=new ViewHolderClass(view);
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ViewHolderClass viewHolderClass = (ViewHolderClass) holder;
CompleteExpenses completeExpenses = completeExpensesList.get(position);
String strName = String.valueOf(completeExpenses.getProduct());
viewHolderClass.pr.setText(strName);
String strCost = String.valueOf(completeExpenses.getCost());
viewHolderClass.cs.setText(strCost);
}
#Override
public int getItemCount() {
return completeExpensesList.size();
}
public class ViewHolderClass extends RecyclerView.ViewHolder{
TextView pr,cs;
public ViewHolderClass(#NonNull View itemView) {
super(itemView);
pr = (TextView) itemView.findViewById(R.id.tv_productname);
cs = (TextView) itemView.findViewById(R.id.tv_costsum);
}
}
}
Java activity:
public class complete_expenses extends AppCompatActivity {
List<CompleteExpenses> completeExpenses;
RecyclerView recyclerView;
Product_Adapter product_adapter;
DatabaseReference databaseReference,databaseReference1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_expenses);
recyclerView=findViewById(R.id.rv_products);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
databaseReference= FirebaseDatabase.getInstance().getReference().child("Project 1").child("CompleteExpenses");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
completeExpenses = new ArrayList<CompleteExpenses>();
CompleteExpenses e = snapshot.getValue(CompleteExpenses.class);
completeExpenses.add(e);
product_adapter=new Product_Adapter(completeExpenses);
recyclerView.setAdapter(product_adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Firebase structure:
You're reading all data from Project 1/CompleteExpenses and are then trying to read a single object with properties cost, date, product and quantity from there.
If we look at your JSON however, the Project 1/CompleteExpenses doesn't have those properties. Instead those properties exist on a child node (and presumably other child nodes) two levels lower in your JSON.
So you'll either need to read data from the lower level in your JSON:
databaseReference= FirebaseDatabase.getInstance().getReference()
.child("Project 1/CompleteExpenses/M-Sand/11-2-2021");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
completeExpenses = new ArrayList<CompleteExpenses>();
CompleteExpenses e = snapshot.getValue(CompleteExpenses.class);
Or you'll need to navigate over the data that you've read in the onDataChange:
databaseReference= FirebaseDatabase.getInstance().getReference().child("Project 1").child("CompleteExpenses");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
completeExpenses = new ArrayList<CompleteExpenses>();
for (DataSnapshot nameSnapshot: snapshot.getChildren()) {
for (DataSnapshot dateSnapshot: nameSnapshot.getChildren()) {
CompleteExpenses e = dateSnapshot.getValue(CompleteExpenses.class);
completeExpenses.add(e);
}
}
product_adapter=new Product_Adapter(completeExpenses);
recyclerView.setAdapter(product_adapter);
}
There is a problem with the data displayed in the recyclerview when I run my program
it looks like this:
.
For the data that is displayed I use firebase like this the
data structure:
When I want to display data in recyclerview in a fragment, but the data doesn't appear. I use Firebase as database
NotaAdapter.java
public class NotaAdapter extends RecyclerView.Adapter<NotaAdapter.MyViewHolder> {
Context context;
ArrayList<ListNota> listnota;
public NotaAdapter (Context c,ArrayList<ListNota> p) {
this.context = c;
this.listnota = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.item_nota, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.no_nota.setText(listnota.get(i).getId_nota());
myViewHolder.total_harga.setText(String.valueOf(listnota.get(i).getTotal_seluruh()));
final String getnoNOta = listnota.get(i).getId_nota();
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoDetailNota = new Intent(context, DetailNotaAct.class);
gotoDetailNota.putExtra("no_nota", getnoNOta);
context.startActivity(gotoDetailNota);
}
});
}
#Override
public int getItemCount() {
return listnota.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView no_nota, total_harga;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
no_nota = itemView.findViewById(R.id.xid_nota);
total_harga = itemView.findViewById(R.id.xtotal_seluruh);
}
}
}
ListNota.java
public class ListNota {
private String id_nota;
private Integer total_seluruh;
public ListNota() {
}
public ListNota(String id_nota, Integer total_seluruh) {
this.id_nota = id_nota;
this.total_seluruh = total_seluruh;
}
public String getId_nota() {
return id_nota;
}
public void setId_nota(String id_nota) {
this.id_nota = id_nota;
}
public Integer getTotal_seluruh() {
return total_seluruh;
}
public void setTotal_seluruh(Integer total_seluruh) {
this.total_seluruh = total_seluruh;
}
}
HistoryFragment.java
public class HistoryFragment extends Fragment {
TextView txt_history, txt_toko, txt_report, txt_nama_toko, txt_jenis_toko;
LinearLayout btn_buat_nota;
DatabaseReference databaseUser, databaseToko, databaseNota;
String USERNAME_KEY = "usernamekey";
String username_key = "";
String username_key_new = "";
String id_Toko = "";
ProgressDialog progress;
RecyclerView nota_place;
ArrayList<ListNota> list;
NotaAdapter notaAdapter;
private View Notaview;
public HistoryFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Notaview = inflater.inflate(R.layout.fragment_history, container, false);
txt_nama_toko = (TextView) Notaview.findViewById(R.id.txt_nama_toko);
txt_jenis_toko = (TextView) Notaview.findViewById(R.id.txt_jenis_toko);
txt_history = (TextView) Notaview.findViewById(R.id.txt_history);
txt_toko = (TextView) Notaview.findViewById(R.id.txt_toko);
txt_report = (TextView) Notaview.findViewById(R.id.txt_report);
btn_buat_nota = (LinearLayout) Notaview.findViewById(R.id.btn_buat_nota);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Memuat Data");
progress.setCancelable(false);
progress.show();
getUsernameLocal();
databaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
id_Toko = dataSnapshot.child("id_toko").getValue().toString();
databaseToko = FirebaseDatabase.getInstance().getReference().child("Toko").child(id_Toko);
databaseToko.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
txt_nama_toko.setText(dataSnapshot.child("nama_toko").getValue().toString());
//cek apakah child jenis toko ada
if (dataSnapshot.hasChild("jenis_toko")){
txt_jenis_toko.setText(dataSnapshot.child(" jenis_toko").getValue().toString());
}else{
txt_jenis_toko.setText("Jenis toko belum disetting");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_buat_nota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id_nota = generateRandomString(16);
Intent gotoBuatNota = new Intent(getActivity(), BuatNotaAct.class);
gotoBuatNota.putExtra("id_nota", id_nota);
startActivity(gotoBuatNota);
}
});
nota_place = (RecyclerView) Notaview.findViewById(R.id.nota_place);
notaAdapter = new NotaAdapter(getContext(), list);
nota_place.setAdapter(notaAdapter);
nota_place.setLayoutManager(new LinearLayoutManager(getActivity()));
return Notaview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<ListNota>();
loaddata();
}
private void loaddata(){
databaseNota = FirebaseDatabase.getInstance().getReference().child("Nota").child(id_Toko);
databaseNota.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
ListNota p = dataSnapshot1.getValue(ListNota.class);
list.add(p);
}
progress.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public String generateRandomString(int length){
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for(int i = 0; i < length; i++){
char c = chars[random.nextInt(chars.length)];
stringBuilder.append(c);
}
return stringBuilder.toString();
}
public void getUsernameLocal(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
username_key_new = sharedPreferences.getString(username_key,"");
}
}
you are reading it from the wrong node, you are passing reference that you want to read data from the node Named "users".
Your Database reference should look like this
databaseUser = FirebaseDatabase.getInstance().getReference("Nota").child("Toko_Kita20082020371").child(username_key_new);
Also make sure your list should have all the variables that a node has.
For example a node has
name,id,price,description;
then same varibles should be declared in your list to successfully ready dta from the firebase.
I'm trying to remove data from my recyclerview and let it be updated in the mobile ui as well. It is an android app. I am able to delete the data alright but I always have to leave that page and come back when I make the changes. I tried making some modifications to the onChildRemoved method but I started getting crashes upon making this change. What do I do? Below is my code.
MainActivity.java
DatabaseReference databaseReference;
List<DataSnapshot> listData;
RecyclerView recyclerView;
MyCart.MyAdapter adapter;
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
listData = new ArrayList<>();
adapter = new MyCart.MyAdapter(listData);
adapter.setHasStableIds(true);
GetDataFirebase();
private void GetDataFirebase() {
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Customers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Items students = dataSnapshot.getValue(Items.class);
listData.add(dataSnapshot);
recyclerView.setAdapter(adapter);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = listData.indexOf(dataSnapshot);
listData.remove(index);
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyCart.MyAdapter.ViewHolder> {
List<DataSnapshot> list;
public MyAdapter(List<DataSnapshot> List) {
this.list = List;
}
#Override
public void onBindViewHolder(MyCart.MyAdapter.ViewHolder holder, int position) {
final DataSnapshot studentSnapshot = list.get(position);
final Items students = studentSnapshot.getValue(Items.class);
final String list_user_id = studentSnapshot.getKey();
holder.item_name.setText(students.getItem_name());
holder.item_price.setText(students.getItem_price());
Picasso.with(holder.item_image.getContext()).load(students.getItem_image()).placeholder(R.drawable.no_image_two).into(holder.item_image);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference prod_ref = FirebaseDatabase.getInstance().getReference().child("Customers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart").child(list_user_id);
prod_ref.removeValue();
adapter.notifyDataSetChanged();
Toast.makeText(MyCart.this, "Item removed from cart", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public MyCart.MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_item_layout, parent, false);
return new MyCart.MyAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView item_name, item_price;
ImageView item_image;
ImageView delete;
public ViewHolder(View itemView) {
super(itemView);
item_name = itemView.findViewById(R.id.item_name);
item_price = itemView.findViewById(R.id.item_price);
item_image = itemView.findViewById(R.id.item_image);
delete = itemView.findViewById(R.id.delete_item);
}
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference prod_ref = FirebaseDatabase.getInstance().getReference().child("Customers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart").child(list_user_id);
prod_ref.removeValue();
//add/modify these two lines here
list.remove(position);
notifyDataSetChanged();
}
});
And one more change you need to do
// move this toast to onChildRemoved method and clear the other code from there
Toast.makeText(MyCart.this, "Item removed from cart", Toast.LENGTH_SHORT).show();
like
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
//remove these line these will raise the exception and Toast here
int index = listData.indexOf(dataSnapshot);
listData.remove(index);
adapter.notifyDataSetChanged();
}
When dataSnapshot does not exist in list, it returns -1. Index of list start from 0. Therefore, you're this getting error. You need to add a guard check here like:
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = listData.indexOf(dataSnapshot);
if(index > 0) {
listData.remove(index);
}
adapter.notifyDataSetChanged();
}
This is my firebase structure
databaseSupp.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
suppList.clear();
for (DataSnapshot suppSnapshot : dataSnapshot.child("Task").getChildren()) {
//Log.d("fbBee", dataSnapshot.getRef().child("Task").child("9223450").child("Firebase").toString());
Log.d("fbBee", suppSnapshot.getValue().toString());
Log.d("fbGet",suppSnapshot.child("Firebase").getValue().toString());
Supp supp = suppSnapshot.child("Firebase").getValue(Supp.class);
suppList.add(supp);
}
SuppList adapter = new SuppList(MainActivity2.this, suppList);
mListViewSupp.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is my code, but this code just show child Firebase. I want read and show data from child Firebase, but I need flag on child Reply for reference in my fragmens. please help for code.
Try something like that:
final DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Task/");
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot taskNo : dataSnapshot.getChildren()) {
// now you in (9223450)
Object firebaseObj = taskNo.child("Firebase").getValue(FirebaseObj.class); //class with params set/get methods
Object replayObj = taskNo.child("Replay").getValue(ReplayObj.class); //class with params set/get methods
// ALTERNATIVE
/*
for (DataSnapshot child : taskNo.getChildren()) {
if(child.getKey().equals("Firebase")) {
String address = child.child("Address").getValue(String.class);
String customer = child.child("Customer").getValue(String.class);
// ...
} else if (child.getKey().equals("Replay")) {
// replay
// ...
}
}
*/
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
Like This
public class SuppList extends ArrayAdapter {
private Activity context;
private List<Supp> suppList;
public SuppList (Activity context, List<Supp> suppList){
super(context, R.layout.list_layout_new, suppList);
this.context = context;
this.suppList = suppList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout_new, null, true);
TextView textViewSo = (TextView) listViewItem.findViewById(R.id.textViewSo);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewAddress = (TextView) listViewItem.findViewById(R.id.textViewAddress);
Supp supp = suppList.get(position);
textViewSo.setText(supp.getSuppId());
//Log.e("SuppTest", supp.getSuppId());
textViewName.setText(supp.getSuppName());
textViewAddress.setText(supp.getSuppAddress());
return listViewItem;
}
}