Sorting FirebaseRecyclerAdapter on Client Side - android

I want to sort FirebaseRecyclerAdapter on the TIME BASIS. I'm working on That Application so whenever new Message comes then That Dialog goes on The Top of the Layout, it also contain time of Sending the Message so The message which is new Then that should be in The Top of the Recyclerview. So So How Can i sort The FirebaseRecyclerAdapter on the Time Basis
Here is me Code
madapter = new FirebaseRecyclerAdapter<user, contact.UserViewHolder>(user.class, R.layout.activity_dialogs_list, contact.UserViewHolder.class, muserref) {
#Override
protected void populateViewHolder(final UserViewHolder viewHolder, user model, final int position) {
final String ais = model.getName();
viewHolder.setName(model.getName());
final String b = model.groupId;
//Toast.makeText(contact.this,viewHolder.getLayoutPosition(),LENGTH_SHORT).show();
mref = FirebaseDatabase.getInstance().getReference().child("LastMessage").child(b);
mref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
val=lmlm;
HashMap<String, Object> hashmap = (HashMap) dataSnapshot.getValue();
val = (String) hashmap.get("lastm");
Long role = (Long) hashmap.get("timestampCreated");
String lastsender = (String) hashmap.get("LastmessageSender");
getTimeago getTimeAgo = new getTimeago();
String lastSeenTime = getTimeAgo.getTimeAgo(role);
//SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
//String dateAsString = sdf.format (role);
//change(position);
// swape(viewHolder.getAdapterPosition());
if (val.length() > 40) {
String nawa = val.substring(0, 40);
viewHolder.setLastmessage((nawa + "..."));
viewHolder.setLastTime(lastSeenTime);
} else {
viewHolder.setLastmessage(val);
viewHolder.setLastTime(lastSeenTime);
}
//viewHolder.setLastmessage(val);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mimage = FirebaseDatabase.getInstance().getReference().child("Image").child(b);
mimage.keepSynced(true);
mimage.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
HashMap<String, Object> hashmap = (HashMap) dataSnapshot.getValue();
final String vala = (String) hashmap.get("image");
viewHolder.setImage(vala, getApplicationContext());
/// //viewHolder.setImage(val,getApplicationContext());
//viewHolder.setImage(vala);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(contact.this,"Something Went wrong",LENGTH_SHORT).show();
}
});
}
});
}
};
mUserlist.setAdapter(madapter);
madapter.notifyDataSetChanged();
And Here is My Holder
`
public static class UserViewHolder extends RecyclerView.ViewHolder {
View mview;
ImageLoader imageLoader;
public UserViewHolder(View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name) {
TextView username = (TextView) mview.findViewById(R.id.dialogName);
username.setText(name);
}
public void setLastmessage(String lastmessage) {
TextView set = (TextView) mview.findViewById(R.id.dialogLastMessage);
set.setText(lastmessage);
}
public void setLastTime(String lastTime) {
TextView time = (TextView) mview.findViewById(R.id.dialogDate);
time.setText(lastTime);
}
public void setImage(final String vala, final Context applicationContext) {
final CircleImageView cm = (CircleImageView) mview.findViewById(R.id.dialogAvatar);
Picasso.with(applicationContext).load(vala).networkPolicy(NetworkPolicy.OFFLINE).into(cm, new Callback() {
#Override
public void onSuccess() {
Picasso.with(applicationContext).load(vala).into(cm);
}
#Override
public void onError() {
Picasso.with(applicationContext).load(vala).into(cm);
}
});
}
`
So if new Message comes in SE Comps then that Dialog Show goes on The Top of RecyclerViewSo How can i get that please Help

Did you try orderByChild function to sort firebase list data?
ref.orderByChild('< time_key >')
OrderByChild will work with ChildEventListner
check this link

Related

Import an firebase image when i click it in the recyclerView?

What I've done alone so far is to bring up a activity (recyclerView of the products) when I click ImageView 1.
When I click on the image of recyclerView, my goal is to load the image I clicked on ImageView 1 and save it in DB.
How can I get an image?
this is my product's adapter
#NonNull
#Override
public HolderProductCody onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_product_seller,parent,false);
return new HolderProductCody(view);
}
#Override
public void onBindViewHolder(#NonNull HolderProductCody holder, int position) {
//get data
final ModelProduct modelProduct = productList.get(position);
String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productColor = modelProduct.getProductColor();
String productTpo = modelProduct.getProductTpo();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String SeasonCategory = modelProduct.getProductSeasonCategory();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
//set data
holder.titleTv.setText(title);
holder.SeasonCategoryTv.setText(SeasonCategory);
holder.tpoTv.setText(productTpo);
holder.colorTv.setText(productColor);
holder.originalPriceTv.setText("$"+originalPrice);
if(detailAvailable.equals("true")){
//product is on discount
holder.tpoTv.setVisibility(View.VISIBLE);
holder.colorTv.setVisibility(View.VISIBLE);
}
else{
//product is not on discount
holder.tpoTv.setVisibility(View.GONE);
holder.colorTv.setVisibility(View.GONE);
}
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(holder.productIconIv);
}
catch(Exception e){
holder.productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
Toast.makeText(context, "클릭됨", Toast.LENGTH_SHORT).show();
//addcodylayout(modelProduct);
}
});
}
private void addcodylayout(ModelProduct modelProduct) {
Dialog dialog = new Dialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.activity_cody_product,null);
dialog.setContentView(view);
dialog.show();
//get data
final String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productTpo = modelProduct.getProductTpo();
String productColor = modelProduct.getProductColor();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
final String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(productIconIv);
}
catch(Exception e){
productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
dialog.show();
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public Filter getFilter() {
if(filter==null){
filter = new FilterProduct(this,filterList);
}
return filter;
}
class HolderProductCody extends RecyclerView.ViewHolder{
/*holds views of recyclerview*/
private ImageView productIconIv;
private TextView tpoTv, titleTv, SeasonCategoryTv,colorTv,originalPriceTv;
public HolderProductCody(#NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
tpoTv = itemView.findViewById(R.id.tpoTv);
titleTv = itemView.findViewById(R.id.titleTv);
SeasonCategoryTv = itemView.findViewById(R.id.categorySeasonTv);
colorTv = itemView.findViewById(R.id.colorTv);
originalPriceTv = itemView.findViewById(R.id.originalPriceTv);
}
}
}
this is my product's activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cody_product);
filterProductBtn = findViewById(R.id.filterProductBtn);
productsRv = findViewById(R.id.productsRv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
getSupportActionBar().hide();
firebaseAuth = FirebaseAuth.getInstance();
filterProductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(CodyProductActivity.this);
builder.setTitle("카테고리 선택").setItems(Constants.productCategories1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//get selected item
String selected = Constants.productCategories1[which];
filteredProductsTv.setText(selected);
if (selected.equals("모든 옷")) {
//load all
loadAllProducts();
} else {
//load filtered
loadFilteredProducts(selected);
}
}
}).show();
}
});
}
private void loadFilteredProducts(String selected) {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for(DataSnapshot ds: dataSnapshot.getChildren()){
String productCategory = ""+ds.child("productCategory").getValue();
//if selected category matches product category then add in list
if(selected.equals(productCategory)){
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this,productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this,3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseerror) {
}
});
}
private void loadAllProducts() {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this, productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this, 3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The ID value of ImageView1 is topImages.

Firebase | How to get the sum of all child entries

The problem when one item value increases the time calculation wrong because the sum value already store. Example: 3 item--- 2+2+2=6 that's right. when 1st item value increases that time 4+2+2=14 (8+previous 6).
Can you help me?
Main focusable part
private void caculatateprice(){
String cccex= uid+"_"+"calculate";
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
int itemTotalPrice = 0;
for (DataSnapshot dataSnapshot : snapshot.child(uid).getChildren()) {
Map<String, Object> tp = (Map<String, Object>) dataSnapshot.getValue();
Object price = tp.get("itemtotalprice");
itemTotalPrice = Integer.parseInt(String.valueOf(price));
subTotal += itemTotalPrice;
finalTotalPrice = subTotal + extraCharge;
subtotal.setText("$" + String.valueOf(subTotal));
deliveryCharge.setText("$" + String.valueOf(extraCharge));
totalPrice.setText("$" + String.valueOf(finalTotalPrice));
}
}
}
java
public class CartFragment extends Fragment {
private RecyclerView recyclerView;
private Button checkOutButton;
private CartItemAdapter itemAdapter;
private ArrayList<CartItemModel> cartItemList;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private FirebaseUser user;
private String uid;
private TextView subtotal,deliveryCharge,totalPrice;
private int subTotal=0,extraCharge=1,finalTotalPrice=0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerView = view.findViewById(R.id.cartrecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
user = firebaseAuth.getCurrentUser();
uid = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("carts");
GetDataFromFirebase();
checkOutButton = view.findViewById(R.id.checkoutbutton);
subtotal = view.findViewById(R.id.subtotalprice);
deliveryCharge = view.findViewById(R.id.deliveryprice);
totalPrice = view.findViewById(R.id.producttotalprice);
caculatateprice();
}
private void caculatateprice(){
String cccex= uid+"_"+"calculate";
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
int itemTotalPrice = 0;
for (DataSnapshot dataSnapshot : snapshot.child(uid).getChildren()) {
Map<String, Object> tp = (Map<String, Object>) dataSnapshot.getValue();
Object price = tp.get("itemtotalprice");
itemTotalPrice = Integer.parseInt(String.valueOf(price));
subTotal += itemTotalPrice;
finalTotalPrice = subTotal + extraCharge;
subtotal.setText("$" + String.valueOf(subTotal));
deliveryCharge.setText("$" + String.valueOf(extraCharge));
totalPrice.setText("$" + String.valueOf(finalTotalPrice));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void GetDataFromFirebase() {
Query query = databaseReference.child(uid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
CartItemModel productItem = new CartItemModel();
productItem.setImage(snapshot.child("image").getValue().toString());
productItem.setName(snapshot.child("name").getValue().toString());
productItem.setPrice(snapshot.child("price").getValue().toString());
productItem.setProductId(snapshot.child("productId").getValue().toString());
productItem.setQuantity(snapshot.child("quantity").getValue().toString());
productItem.setItemtotalprice(snapshot.child("itemtotalprice").getValue().toString());
cartItemList.add(productItem);
}
itemAdapter = new CartItemAdapter(getActivity(),cartItemList);
recyclerView.setAdapter(itemAdapter);
itemAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if (cartItemList!=null){
cartItemList.clear();
if (itemAdapter!=null){
itemAdapter.notifyDataSetChanged();
}
}
cartItemList = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cart, container, false);
return view;
}
}
Adapter class
public class CartItemAdapter extends RecyclerView.Adapter<CartItemAdapter.CartItemViewHolder> {
private int intquantity,itemTotalPrice,itemprice,subTotal,extraCharge=1,finalTotalPrice;
String cartId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("carts").child(cartId);
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("carts");
private Context context;
private ArrayList<CartItemModel> cartItem;
public CartItemAdapter(Context context, ArrayList<CartItemModel> cartItem) {
this.context = context;
this.cartItem = cartItem;
}
#NonNull
#Override
public CartItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_item_card, parent, false);
return new CartItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CartItemViewHolder holder, int position) {
String ccc= cartId+"_"+cartItem.get(position).getProductId();
// String cccex= cartId+"_"+"calculate";
holder.itemname.setText(cartItem.get(position).getName());
holder.itemprice.setText("$"+cartItem.get(position).getPrice());
Glide.with(context).load(cartItem.get(position).getImage()).into(holder.itemimage);
holder.quantityitem.setText(cartItem.get(position).getQuantity());
holder.itemtotalprice.setText("$"+cartItem.get(position).getItemtotalprice());
holder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quantity = cartItem.get(position).getQuantity();
intquantity =Integer.parseInt(quantity.toString());
String itemPrice = cartItem.get(position).getPrice();
itemprice =Integer.parseInt(itemPrice.toString());
if(intquantity>0){
intquantity--;
}
itemTotalPrice = intquantity*itemprice;
HashMap<String, Object> result = new HashMap<>();
result.put("quantity", intquantity);
result.put("itemtotalprice",itemTotalPrice);
databaseReference.child(ccc).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
// subTotal = subTotal+itemTotalPrice;
// finalTotalPrice=subTotal+extraCharge;
// HashMap<String, Object> totalresult = new HashMap<>();
// totalresult.put("subtotal", subTotal);
// totalresult.put("totalprice",finalTotalPrice);
//
// databaseReference1.child(cccex).updateChildren(totalresult)
// .addOnSuccessListener(new OnSuccessListener<Void>() {
// #Override
// public void onSuccess(Void aVoid) {
//
// }
// });
}
});
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quantity = cartItem.get(position).getQuantity();
intquantity =Integer.parseInt(quantity.toString());
String itemPrice = cartItem.get(position).getPrice();
itemprice =Integer.parseInt(itemPrice.toString());
intquantity++;
itemTotalPrice = intquantity*itemprice;
HashMap<String, Object> result = new HashMap<>();
result.put("quantity", intquantity);
result.put("itemtotalprice",itemTotalPrice);
databaseReference.child(ccc).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
// subTotal = subTotal+itemTotalPrice;
// finalTotalPrice=subTotal+extraCharge;
// HashMap<String, Object>totalresult = new HashMap<>();
// totalresult.put("subtotal", subTotal);
// totalresult.put("totalprice",finalTotalPrice);
//
// databaseReference1.child(cccex).updateChildren(totalresult)
// .addOnSuccessListener(new OnSuccessListener<Void>(){
// #Override
// public void onSuccess(Void aVoid){
//
// }
// });
}
});
holder.cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.child(ccc).removeValue();
Toast.makeText(context,"Item Removed from Cart",Toast.LENGTH_SHORT).show();
cartItem.remove(position);
notifyItemChanged(position);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return cartItem.size();
}
public static final class CartItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemname, itemprice, quantityitem, itemtotalprice;
private ImageView itemimage, minus, plus, cross;
public CartItemViewHolder(#NonNull View itemView) {
super(itemView);
itemname = itemView.findViewById(R.id.product_name);
itemprice = itemView.findViewById(R.id.product_price);
itemimage = itemView.findViewById(R.id.product_image);
quantityitem = itemView.findViewById(R.id.itemcount);
itemtotalprice = itemView.findViewById(R.id.itemtotalprice);
minus = itemView.findViewById(R.id.itemminus);
plus = itemView.findViewById(R.id.itemplus);
cross = itemView.findViewById(R.id.itemdelete);
}
}
}
database
{
"carts" : {
"6OD9qfVX9LMN4CoWb6qmSJvXTlf2" : {
"6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1002" : {
"id" : "6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1002",
"image" : "https://n4.sdlcdn.com/imgs/i/z/i/HMTe-HM-9072-Metal-Analog-SDL494827480-1-db8fc.jpg",
"itemtotalprice" : "390",
"name" : "Metal Analog",
"price" : "390",
"productId" : "1002",
"quantity" : "1"
},
"6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1008" : {
"id" : "6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1008",
"image" : "https://cdn4.ethoswatches.com/the-watch-guide/wp-content/uploads/2017/06/Top-10-Casio-G-Shock-Watches-Post-mobile-mast.jpg",
"itemtotalprice" : "80",
"name" : "G-Shock(casio)",
"price" : "80",
"productId" : "1008",
"quantity" : "1"
}
}
},
}

Dynamic Expandable Recyclerview List Failing

I'm new to Android and I know this might be a piece of cake but I'm struggling.
I was trying to create a dynamic expandable recycler view using firebase realtime database but the data is not displaying properly.
I'm passing a string from one activity to another and comparing the string to the database field and then displaying it's child components but I don't know where I'm failing.
I want to display the Parent and child field by comparing the name field with the value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_detail);
//string value from another activity
String value = getIntent().getExtras().getString("name");
recycler_view = (RecyclerView) findViewById(R.id.recycler_expand);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference parentReference = database.getReference().child("Tutors");
//comparing
parentReference.equalTo(value).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ParentList> Parent = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String ParentKey = snapshot.getKey().toString();
snapshot.child("title").getValue();
DatabaseReference childReference =
FirebaseDatabase.getInstance().getReference().child(ParentKey);
childReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ChildList> Child = new ArrayList<>();
for (DataSnapshot snapshot1:dataSnapshot.getChildren())
{
final String ChildValue = snapshot1.getValue().toString();
snapshot1.child("title").getValue();
Child.add(new ChildList(ChildValue));
}
Parent.add(new ParentList(ParentKey, Child));
DocExpandableRecyclerAdapter adapter = new DocExpandableRecyclerAdapter(Parent);
recycler_view.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database Structure
ChildList.java
public class ChildList implements Parcelable {
private String title;
public ChildList(String title) {
this.title = title;
}
protected ChildList(Parcel in) {
title = in.readString();
}
public static final Creator<ChildList> CREATOR = new Creator<ChildList>() {
#Override
public ChildList createFromParcel(Parcel in) {
return new ChildList(in);
}
#Override
public ChildList[] newArray(int size) {
return new ChildList[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String Title) {
this.title = Title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
}
}
Please anyone help me with this :(
Don't use equalTo().
Try this:
DatabaseReference parentReference = database.getReference().child("Tutors");
parentReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String NameKey = snapshot.getKey().toString();
if(value.equals(NameKey)){
//DO WHATEVER YOU WANT
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to retrieve values from FireBase to JSONArray?

I got a source code of a food delivery app from git. he is parsing a website and displaying the menu items, I guess to see the
instead of this I have created a fire-base database and stored one food item for testing
I want to display my item from the fire-base to the app menu I will show the code of all food item fragment,
package com.example.guanzhuli.foody.HomePage.fragment;
public class AllTabFragment extends Fragment {
private String baseUrl = "http://rjtmobile.com/ansari/fos/fosapp/fos_food_loc.php?city=";
private String TAG = "ALLFOOD";
private StorageReference mStorageRef;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
ArrayList<Food> foods = new ArrayList<>();
private RecyclerView mRecyclerView;
private AllFoodAdapter adapter;
private RecyclerView.LayoutManager layoutManager;
String foodName;
public AllTabFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_tab, container, false);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
Toast.makeText(getActivity(), foodName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Request Data From Web Service
if (foods.size() == 0) {
objRequestMethod();
}
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_all);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new AllFoodAdapter(getActivity(), foods);
adapter.setOnItemClickListener(new AllFoodAdapter.OnRecyclerViewItemClickListener() {
#Override
public void onItemClick(View view, String data) {
Bundle itemInfo = new Bundle();
for (int i = 0; i < foods.size(); i++) {
if (foods.get(i).getId() == Integer.valueOf(data)) {
itemInfo.putInt("foodId", foods.get(i).getId());
itemInfo.putString("foodName", foods.get(i).getName());
// itemInfo.putString("foodName", foodName);
itemInfo.putString("foodCat", foods.get(i).getCategory());
itemInfo.putString("foodRec", foods.get(i).getRecepiee());
itemInfo.putDouble("foodPrice", foods.get(i).getPrice());
itemInfo.putString("foodImage", foods.get(i).getImageUrl());
break;
}
}
FoodDetailFragment foodDetailFragment = new FoodDetailFragment();
foodDetailFragment.setArguments(itemInfo);
getActivity().getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out)
.replace(R.id.main_fragment_container, foodDetailFragment)
.addToBackStack(AllTabFragment.class.getName())
.commit();
}
});
mRecyclerView.setAdapter(adapter);
return view;
}
private void objRequestMethod() {
HomePageActivity.showPDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, buildUrl(), null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, jsonObject.toString());
try {
JSONArray foodsJsonArr = jsonObject.getJSONArray("Food");
for (int i = 0; i < foodsJsonArr.length(); i++) {
JSONObject c = foodsJsonArr.getJSONObject(i);
String id = c.getString("FoodId");
String name = c.getString("FoodName");
String recepiee = c.getString("FoodRecepiee");
String price = c.getString("FoodPrice");
String category = c.getString("FoodCategory");
String thumb = c.getString("FoodThumb");
final Food curFood = new Food();
curFood.setCategory(category);
curFood.setName(name);
curFood.setRecepiee(recepiee);
curFood.setPrice(Double.valueOf(price));
curFood.setId(Integer.valueOf(id));
curFood.setImageUrl(thumb);
foods.add(curFood);
// Log.e("Current Food", curFood.getName());
ImageLoader imageLoader = VolleyController.getInstance().getImageLoader();
imageLoader.get(thumb, new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
}
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
curFood.setImage(response.getBitmap());
// Log.e("SET IMAGE", curFood.getName());
adapter.notifyData(foods);
}
}
});
foods.get(i).setImage(curFood.getImage());
}
} catch (Exception e) {
System.out.println(e);
}
HomePageActivity.disPDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG, "ERROR" + volleyError.getMessage());
Toast.makeText(getActivity(), volleyError.getMessage(),
Toast.LENGTH_SHORT).show();
HomePageActivity.disPDialog();
}
});
VolleyController.getInstance().addToRequestQueue(jsonObjReq);
}
private String buildUrl() {
return baseUrl + HomePageActivity.City;
}
}
I got food name from fire-base and stored in the string called "foodname" Now I want to display it in the menu, how can I do it?
if my question is wrong please forgive me, please help me
package com.example.guanzhuli.foody.HomePage.adapter;
public class AllFoodAdapter extends RecyclerView.Adapter<AllHolder> implements
View.OnClickListener {
private Context mContext;
ArrayList<Food> foods;
public String TAG = "ALLFOOD";
//
// public AllFoodAdapter(Context context) {
// mContext = context;
// }
public AllFoodAdapter(Context context, ArrayList<Food> foods) {
mContext = context;
this.foods = foods;
}
#Override
public AllHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.cardview_food, parent, false);
AllHolder allHolder = new AllHolder(v);
v.setOnClickListener(this);
return allHolder;
}
#Override
public void onBindViewHolder(AllHolder holder, int position) {
holder.mTextId.setText(String.valueOf(foods.get(position).getId()));
holder.mTextName.setText(foods.get(position).getName());
holder.mTextPrice.setText(String.valueOf(foods.get(position).getPrice()));
holder.mTextCategory.setText(foods.get(position).getCategory());
holder.mImageView.setImageBitmap(foods.get(position).getImage());
holder.itemView.setTag(foods.get(position).getId());
}
#Override
public int getItemCount() {
return foods.size();
}
public void notifyData(ArrayList<Food> foods) {
// Log.d("notifyData ", foods.size() + "");
this.foods = foods;
notifyDataSetChanged();
}
public static interface OnRecyclerViewItemClickListener {
void onItemClick(View view, String data);
}
private OnRecyclerViewItemClickListener mOnItemClickListener = null;
public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
this.mOnItemClickListener = listener;
}
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, String.valueOf(view.getTag()));
} else {
Log.e("CLICK", "ERROR");
}
}
}
class AllHolder extends RecyclerView.ViewHolder {
NetworkImageView mImage;
ImageView mImageView;
TextView mTextId, mTextName, mTextCategory, mTextPrice;
public AllHolder(View itemView) {
super(itemView);
// mImage = (NetworkImageView) itemView.findViewById(R.id.food_img);
mImageView = (ImageView) itemView.findViewById(R.id.food_img);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextName = (TextView) itemView.findViewById(R.id.food_name);
mTextPrice = (TextView) itemView.findViewById(R.id.food_price);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextCategory = (TextView) itemView.findViewById(R.id.food_category);
}
}
Please help me, because it is an important project for me
If you want to display the strings you have received from firebase in a new activity as a list, you can declare an ArrayList and then add those strings to it and then with an adapter set it to display.
In code it looks something like this:
private ArrayList array;
private ListView listView;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private String curName;
//set them
listView = findViewById(R.id.list1);
array = new ArrayList<String>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
array.add(ds.child("name").getValue(String.class));
}
ArrayAdapter adapter = new ArrayAdapter(Main6Activity.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
stackoverflow was not conceived to get complete code solutions. We can only help you on some point. Other than that, you need to think to use the Food class for read and write values on your db. When you retrive the values, get it as a Food object casting it by method dataSnapshot.getValue("object class");...
In your case you need a code like this:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Food food = snapshot.getValue(Food.class);
//here you need to add the food object to a list and after the for diplay it with adapter.
//for example foodsList.add(food);
}
foodsList.setAdapter(myAdepter); //ecc
}
If you need help, please tell us more
You seem to be loading the food items from the database, and reading the values from them. All that's left to do, is add each item to the foods array, and tell the adapter that its data has changed:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue(String.class);
String foodPrice = snapshot.child("prize").getValue(String.class);
Food food = new Food();
food.setName(name);
food.setPrice(Double.valueOf(price));
foods.add(food);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

Unable to display all images from firebase database and I want to show all images from one id into grid view

This is my firebase storage image and I want to display all images from url into gridview by taking the current user id
This is my main activity onstart() that leads to adapter class.
I want to show all the images under current user id like grid view.
How to display all user image posts in grid view from firebase above image.
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
uploads = new ArrayList<Blog>();
if (currentUser != null && !currentUser.isAnonymous()) {
mUserf.child("online").setValue("true");
mProgressbar.setMessage("Welcome.....");
mProgressbar.show();
mProgressbar.dismiss();
ConnectivityManager check = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = check.getActiveNetworkInfo(); //for checking whether app is connected to a network or not..
if(info!=null && info.isConnected()) {
//Toast.makeText(MainActivity.this, "network available", Toast.LENGTH_SHORT).show();
firebaseAuth.addAuthStateListener(authStateListener);
mProgressbar.setMessage("Fetching Blogs.....");
mProgressbar.show();
mProgressbar.dismiss();
list = new ArrayList<>();
adapter = new MyCustomAdapter(this,list,firebaseAuth,mdatabaseReference,likesdatabaseReference);
recyclerView = (RecyclerView) findViewById(R.id.blog_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
alpha = FirebaseDatabase.getInstance().getReference().child("Blog").child(mAuth.getCurrentUser().getUid());
mchildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mProgressbar.dismiss();
String j = dataSnapshot.getKey();
Log.v("GETKEYZZZ", j);
Blog friendlyMessage = dataSnapshot.getValue(Blog.class);
friendlyMessage.setPostkey(j);
list.add(friendlyMessage);
adapter.notifyDataSetChanged();
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot){}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mquery.addChildEventListener(mchildEventListener);
} else {
//Toast.makeText(MainActivity.this, "No network available", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Please Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
// mDatabseUsers.child("online").setValue("true");
} else {
Intent user1 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(user1);
}
}
This is my adapter class where
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.myviewholder> {
Context context;
ArrayList<Blog> list;
List <String> imageUrls;
//List<String> imageUrls ;
LayoutInflater inflator;
int lastPosition = 1;
boolean mprogressLike = true,mprogressview = true;
DatabaseReference likeDatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference blogDatabaseReference;
public MyCustomAdapter(Context context, ArrayList<Blog> list,FirebaseAuth firebaseAuth,DatabaseReference blogDatabaseReference, DatabaseReference likeDatabaseReference) {
this.context=context;
this.list=list;
inflator=LayoutInflater.from(context);
this.likeDatabaseReference=likeDatabaseReference;
this.firebaseAuth=firebaseAuth;
this.blogDatabaseReference=blogDatabaseReference;
}
#Override
public myviewholder onCreateViewHolder(ViewGroup parent, int position) {
View v=inflator.inflate(R.layout.posts,parent,false);//this view will contain appearance of each layout i.e each row..
myviewholder holder=new myviewholder(v);// we are passing the view of each row to the myviewholder class
return holder;
}
#Override
public void onBindViewHolder(final myviewholder holder, int position) {//here we will inflate datas in the widgets i.e image and title..
//It is called for each row..so every row is inflated here..
final Blog p=list.get(position);
holder.title.setText(p.getTitle());
holder.username.setText(p.getUsername());
holder.viewno.setText(p.getTimestamp());
/*int count = 0;
for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
count += images.size();
}*/
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
Picasso.with(context).load(imageUrls.get(position)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(position));
}
Picasso.with(context).load(p.getImage()).into(holder.userdp);
}
#Override
public int getItemCount() {
return list.size();
}
public class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
// It contains the elements in each row that we will inflate in the recyclerView..
TextView title,desc,username,likeno,viewno;
ImageView imageview,userdp, over, comments, likes;
ImageButton likebtn,viewbtn;
public myviewholder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.blog_desc);//here we link with the elements of each view i.e each row and
// desc = (TextView) itemView.findViewById(R.id.postdesc);//here we link with the elements of each view i.e each row and
username = (TextView) itemView.findViewById(R.id.blog_user_name);
viewno = (TextView) itemView.findViewById(R.id.blog_date);
likeno = (TextView) itemView.findViewById(R.id.blog_like_count);
userdp = (ImageView) itemView.findViewById(R.id.blog_user_image);
imageview = (ImageView) itemView.findViewById(R.id.blog_image);
comments = (ImageView) itemView.findViewById(R.id.blog_comment_icon);
//here we link with the elements of each view i.e each row and
// likebtn = (ImageButton)itemView.findViewById(R.id.likebtn);
// viewbtn = (ImageButton)itemView.findViewById(R.id.viewbtn);
comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mprogressview = true;
int pos = getAdapterPosition();
Blog b = list.get(pos);
Intent intent = new Intent(context,CommentBox.class);
Bundle bundle = new Bundle();
bundle.putString("post_key",b.getUid().toString());
intent.putExtras(bundle);
context.startActivity(intent);
}
});
over = (ImageView) itemView.findViewById(R.id.overflow);
over.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFilterPopup(v);
}
});
});
itemView.setOnClickListener(this);
}
}
To display all those url's, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference urlRef = rootRef.child("Blog").child(uid).child("url");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
urlRef.addListenerForSingleValueEvent(valueEventListener);
And here is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter.
Edit:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Blog").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uid = dataSnapshot.child("uid").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String timestamp = dataSnapshot.child("timestamp").getValue(String.class);
Log.d("TAG", uid + " / " + title + " / " + timestamp);
for(DataSnapshot ds : dataSnapshot.child("url").getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Categories

Resources