I have OrderCart from where I want to get sum of all the item prices so that it displays total price to the user
this is my Order class which has string price attribute
public class Order {
private String mID;
private String mName;
private String mPrice;
public Order(){
}
public Order(String id, String name, String price)
{
mID = id;
mName = name;
mPrice = price;
}
public String getmID() {
return mID;
}
public String getmName() {
return mName;
}
public String getmPrice() {
return mPrice;
}
and this is class where firebase adopter to retrieve data is present. The adopter displays all the children under OrderCart parent and total sum should be display below the adopter but it is giving errors
public class PlaceOrder extends AppCompatActivity {
private RecyclerView mOrderList;
private DatabaseReference mDatabase;
private int total_amount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_orders);
mOrderList = (RecyclerView) findViewById(R.id.order_layout);
mOrderList.setHasFixedSize(true);
mOrderList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("OrderCart");
FirebaseRecyclerAdapter<Order, OrderViewHolder> FBRA = new FirebaseRecyclerAdapter<Order, OrderViewHolder>(
Order.class,
R.layout.single_order,
OrderViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(OrderViewHolder viewHolder, Order model, int position) {
viewHolder.setmID(model.getmID());
viewHolder.setmName(model.getmName());
viewHolder.setmPrice(model.getmPrice());
}
};
mOrderList.setAdapter(FBRA);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapScore : dataSnapshot.child("OrderCart").getChildren()) {
total_amount += Integer.parseInt(String.valueOf(snapScore.child("mPrice").getValue()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
TextView item_price = (TextView) findViewById(R.id.price);
item_price.setText(total_amount);
}
now when I try to display total amount, the app collapse so how can I properly retrieve the data?
Try this way, use iterator to read the data.
Inside onDataChange,
Iterator<DataSnapshot> dataSnapshotsorder = dataSnapshot.child("OrderCart").getChildren().iterator();
while (dataSnapshotsorder .hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
total_amount += Integer.parseInt(String.valueOf(dataSnapshotChild .child("mPrice").getValue()));
}
Related
this is my db structure
I have a list of passenger and i want to retrive them from the firebase database if the passenger list contains more than one passenger then i want to get those data show in one textView. But everytime it generates 2 textView if there were two passenger. I want in all cases it shows all the data in just one TextView.
This is my model Class`
public class RetrieveTickets {
private String name;
private String age;
private String gender;
public RetrieveTickets() {
}
public RetrieveTickets(String name, String age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public List<HashMap<String,Object>> toList(){
List<HashMap<String,Object>> list=new ArrayList<>();
HashMap<String,Object> map=new HashMap<>();
map.put("name",getName());
map.put("age",getAge());
map.put("gender",getGender());
list.add(map);
return list;
}
}
this is MyActivity where i am showing the data
public class MyBookingsActivity extends AppCompatActivity{
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth mAuth;
private FirebaseRecyclerAdapter<RetrieveTickets, BookingHolder> firebaseRecyclerAdapter;
public static List<String> trips=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_bookings);
recyclerView = (RecyclerView) findViewById(R.id.my_bookings);
recyclerView.setHasFixedSize(true);
String tripId = getIntent().getStringExtra("TripId");
trips.add(tripId);
// String bookingId = getIntent().getStringExtra("BookingId");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.child("BooKings").child(userId).child(tripId).child("passenger");
FirebaseRecyclerOptions<RetrieveTickets> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<RetrieveTickets>()
.setQuery(query, RetrieveTickets.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<RetrieveTickets, BookingHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull BookingHolder holder, int position, #NonNull RetrieveTickets model) {
holder.setPassengers(model);
}
#NonNull
#Override
public BookingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tickets, parent, false);
return new BookingHolder(view);
}
#Override
public void onError(#NonNull DatabaseError error) {
super.onError(error);
Toast.makeText(MyBookingsActivity.this,"error"+error,Toast.LENGTH_LONG).show();
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null) {
firebaseRecyclerAdapter.stopListening();
}
}
public static class BookingHolder extends RecyclerView.ViewHolder{
private TextView passenger;
public BookingHolder(#NonNull View itemView) {
super(itemView);
passenger=(TextView)itemView.findViewById(R.id.passenger);
}
void setPassengers(RetrieveTickets retrieveTickets) {
passenger.setText(retrieveTickets.toList().toString());
}
}
If you want to display all passengers in one TextView then you shouldn't do like this... Right now you are using RecyclerView and it will make rows == number of passengers and its exactly why we use RecyclerView
If you want to show PassengerList in one textView do like this
StringBuilder passengerStrBuilder = new StringBuilder();
for (String details : yourList) {
passengerStrBuilder.append(details + "\n");
}
textView.setText(passengerStrBuilder.toString());
Here yourList is Passenger List
I want to draw boolean data from the database, but my code is wrong. How do I assign boolean data to the getstate variable? I want to assign the data in the database to the getstate variable in the product class. How do I do it?
I get this error on the line :
productList.add(p.getStates());
: I am getting the error:
list cannot be applied to boolean
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
final DatabaseReference ref = mDatabase.child("0").child("states");
List<Product> productList;
dbProducts.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
productList = new ArrayList<>();
if(dataSnapshot.exists()){
for(DataSnapshot productSnapshot : dataSnapshot.getChildren()){
Product p = productSnapshot.getValue(Product.class);
productList.add(p);
}
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Product p = snapshot.getValue(Product.class);
productList.add(p.getStates());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
public class Product {
private String places;
private String time;
private String title;
private String id;
private boolean States;
public Product(){
}
public Product(String places, String time, String title, String id, boolean States) {
this.places = places;
this.time = time;
this.title = title;
this.id = id;
this.States = States;
}
public String getplaces() {
return places;
}
public String gettime() {
return time;
}
public String gettitle() {
return title;
}
public String getid() {
return id;
}
public boolean getStates() {
return States;
}
}
You are trying to add a Boolean value in a list that cotains a Product. The correct way to do it is:
productList.add(p);
I have an array of data which I am retrieving from firebase. I am using a recyclerview to display the data but my adapter is not working correctly.I tried adding the arraylist in the adapter but this is not working.
It is saying the adapter is not attached and I am having a blank activity.
Any help on this ?
Here are my details.
Modal Class
public class Order {
private String ProductId;
private String ProductName;
private String Quantity;
public Order() {
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getProductName() {
return ProductName;
}
public void setProductName(String productName) {
ProductName = productName;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public Order(String productId, String productName, String quantity) {
ProductId = productId;
ProductName = productName;
Quantity = quantity;
}
}
Adapter
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersViewHolder> {
List<Order> myfoods;
public AllOrdersAdapter(List<Order> myfoods) {
this.myfoods = myfoods;
}
#NonNull
#Override
public AllOrdersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.allorders_layout,parent,false);
return new AllOrdersViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull AllOrdersViewHolder holder, int position) {
holder.foodname.setText(myfoods.get(position).getProductName());
holder.foodquantity.setText(myfoods.get(position).getQuantity());
holder.foodId.setText(myfoods.get(position).getProductId());
}
#Override
public int getItemCount() {
return myfoods.size();
}
}
Test Class
public class Test extends AppCompatActivity {
FirebaseDatabase db;
DatabaseReference requests;
RecyclerView lstFoods;
RecyclerView.LayoutManager layoutManager;
TextView food_id,food_quan,food_name;
// List foods = new ArrayList<>();
// RecyclerView.Adapter<AllOrder> adapter;
// List<String> myOrders = new ArrayList<String>();
// ArrayList<String> foods=new ArrayList<>();
List<String> myfoods = new ArrayList<String>();
AllOrdersAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//firebase
db = FirebaseDatabase.getInstance();
requests= db.getReference().child("Requests");
lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstFoods.setLayoutManager(layoutManager);
loadOrderss();
}
private void loadOrderss() {
requests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.getValue() != null) {
// List ingredients = new ArrayList<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
// String data = String.valueOf(postSnapshot.getValue(Order.class));
myfoods.add(ing.child("quantity").getValue(String.class));
myfoods.add(ing.child("productName").getValue(String.class));
myfoods.add(ing.child("productId").getValue(String.class));
// myfoods.add(String.valueOf(Order.class));
System.out.println("Gained data: " + ing.child("productName").getValue(String.class));
}
}
}
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
lstFoods.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
There seems to be a couple things wrong with the code. As it is posted I would be surprised if it compiles.
In your Adapter you have:
List<Order> myfoods;
and
public AllOrdersAdapter(List<Order> myfoods) {
this.myfoods = myfoods;
}
but in your activity code you pass:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
one is a ArrayList of String the other of Order !
You also need to change your adapter class to something like:
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersAdapter.AllOrdersViewHolder> {
private static final String TAG = AllOrdersAdapter.class.getSimpleName();
private ArrayList<Order> mData;
public class AllOrdersViewHolder extends RecyclerView.ViewHolder {
public TextView mTvFoodname;
public TextView mTvFoodQuantity;
public TextView mTvFoodId;
public AllOrdersViewHolder(View v){
super(v);
// TODO: You need to assign the appropriate View Id's instead of the placeholders ????
mTvFoodQuantity = v.findViewById(R.id.????);
mTvFoodname = v.findViewById(R.id.????);
mTvFoodId = v.findViewById(R.id.????);
}
}
public AllOrdersAdapter(ArrayList<Order> data){
this.mData = data;
}
#Override
public AllOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.business_list_card_view, parent, false);
return new AllOrdersViewHolder(itemView);
}
#Override
public void onBindViewHolder(final AllOrdersViewHolder holder, final int position){
//TODO: You need to decide whether you want to pass a string or order object
Order data = mData.get(position);
final String name = data.getProductName();
final String quantity = data.getQuantity();
final String id = data.getProductId();
holder.mTvFoodname.setText(name);
holder.mTvFoodQuantity.setText(quantity );
holder.mTvFoodId.setText(id)
}
#Override
public int getItemCount(){
return mData.size();
}
}
Note: That since I can not know, whether an ArrayList of String or of Order should be used the parameters in either the Activity or Adapter will need to be changed. Also how you assign the data to the RecyclerView will be affected in the onBindViewHolder method.
You should also follow the advice given by Frank.
EDIT
Change your onDataChange() method to this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.getValue() != null) {
List ingredients = new ArrayList<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
String name = ing.child("productName").getValue(String.class);
String quantity = ing.child("quantity").getValue(String.class);
String productId = ing.child("productId").getValue(String.class);
// Using your overloaded class constructor to populate the Order data
Order order = new Order(productId, name, quantity);
// here we are adding the order to the ArrayList
myfoods.add(order);
Log.e(TAG, "Gained data: " + name)
}
}
}
adapter.notifyDataSetChanged();
}
In your Activity you will need to change the ArrayList class variable "myfoods" to this:
ArrayList(Order) myfoods = new ArrayList<>();
and in your onCreate() method you can now change:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
to simply this:
adapter = new AllOrdersAdapter(myfoods);
Also notice that I have made some changes in my original code above.
You'll want to create the adapter, and attach it to the view, straight in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//firebase
db = FirebaseDatabase.getInstance();
requests= db.getReference().child("Requests");
lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstFoods.setLayoutManager(layoutManager);
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
lstFoods.setAdapter(adapter);
loadOrders();
}
This also means you should declare myfoods as a ArrayList<String>, which saves you from having to downcast it. Something like:
ArrayList<String> myfoods = new ArrayList<String>();
Now in loadOrders you simple add the items to the list, and then notify the adapter that its data has changed (so that it repaints the view):
private void loadOrders() {
requests.child("foods").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot ing: postSnapshot.getChildren()) {
myfoods.add(ing.child("quantity").getValue(String.class));
myfoods.add(ing.child("productName").getValue(String.class));
myfoods.add(ing.child("productId").getValue(String.class));
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
I am making an android app ,which is get order from customers,but i faced a problem . I am trying to Retrieve Data from Firebase and display in a list view. I can get the data back from Firebase but when it displays in the listview it just displays one data in many times. I want to be displayed on one line for each record. Can anyone see where i am going wrong??
Database Image
ListView Image
OrderHistory
public class OrderHistory
{
String ammount,photoId,trxId,name,copy,photoSize,date;
public OrderHistory(String name,String photoId,String trxId,String copy,String photoSize,String ammount,String date)
{
this.name = name;
this.ammount = ammount;
this.photoId = photoId;
this.copy = copy;
this.photoSize = photoSize;
this.trxId = trxId;
this.date = date;
}
public String getAmmount() {
return ammount;
}
public void setAmmount(String ammount) {
this.ammount = ammount;
}
public String getPhotoId() {
return photoId;
}
public void setPhotoId(String photoId) {
this.photoId = photoId;
}
public String getTrxId() {
return trxId;
}
public void setTrxId(String trxId) {
this.trxId = trxId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCopy() {
return copy;
}
public void setCopy(String copy) {
this.copy = copy;
}
public String getPhotoSize() {
return photoSize;
}
public void setPhotoSize(String photoSize) {
this.photoSize = photoSize;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
OrderHistoryAdapter
public class OrderHistoryAdapter extends BaseAdapter {
private List<OrderHistory> orderHistories;
Context context;
public OrderHistoryAdapter(Context context, List<OrderHistory> myOrderInformations) {
this.context = context;
this.orderHistories = myOrderInformations;
}
#Override
public int getCount() {
return orderHistories.size();
}
#Override
public Object getItem(int position) {
return orderHistories.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.show_my_order_history, parent, false);
final TextView txtName, txtdate, txtPhotoId, trxId,txtAmount,txtPhotoSize,txtCopy;
txtName = (TextView)view.findViewById(R.id.txtName);
txtdate = (TextView)view.findViewById(R.id.txtDate);
txtPhotoId = (TextView)view.findViewById(R.id.txtPhotoId);
trxId = (TextView)view.findViewById(R.id.txtTrx);
txtAmount = (TextView)view.findViewById(R.id.txtAmount);
txtPhotoSize = (TextView)view.findViewById(R.id.txtSize);
txtCopy = (TextView)view.findViewById(R.id.txtCopy);
txtName.setText(orderHistories.get(position).getName());
txtdate.setText(orderHistories.get(position).getDate());
txtPhotoId.setText(orderHistories.get(position).getPhotoId());
trxId.setText(orderHistories.get(position).getTrxId());
txtAmount.setText(orderHistories.get(position).getAmmount());
txtCopy.setText(orderHistories.get(position).getCopy());
txtPhotoSize.setText(orderHistories.get(position).getPhotoSize());
return view;
}
}
OrderHistoryList
public class OrderHistoryList extends AppCompatActivity
{
private DatabaseReference databaseReference;
private List<OrderHistory> orderHistories;
private static String phoneNumber;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_my_order);
Firebase.setAndroidContext(this);
listView = (ListView)findViewById(R.id.listView);
getAllOrderFromFirebase();
}
private void getAllOrderFromFirebase()
{
orderHistories = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("order");
String phone = getIntent().getExtras().getString("phone");
databaseReference.orderByChild("phone").equalTo(phone).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String amount, photoId, trxId, name, copy, photoSize, date;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
name = snapshot.child("name").getValue(String.class);
photoId = snapshot.child("photoId").getValue(String.class);
amount = snapshot.child("totalAmount").getValue(String.class);
trxId = snapshot.child("trxId").getValue(String.class);
photoSize = snapshot.child("photoSize").getValue(String.class);
date = snapshot.child("date").getValue(String.class);
copy = snapshot.child("totalCopy").getValue(String.class);
orderHistories.add(new OrderHistory(name, photoId, trxId, copy, photoSize, amount, date));
}
OrderHistoryAdapter adapter;
adapter = new OrderHistoryAdapter(OrderHistoryList.this, orderHistories);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#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) {
}
});
}
}
I guess your problem is by the way you refer to your data so instead of this
databaseReference = FirebaseDatabase.getInstance().getReference("order");
use this
databaseReference = FirebaseDatabase.getInstance().getReference().child("order");
and you didn't use a query object to query your database reference
so now you don't query directly from databaseReference like the way you did it
instead you do this:
Query query=databaseReference.orderByChild("phone").equalTo(phone);
once you have a query that fits you now add on child listener and continue the rest of your code:
query.addChildEventListener(new ChildEventListener() {
//the rest of your code goes here(on child added/changed/......)
)};
I am trying to push an Object of a class to Firebase by defining the function in that class itself, but I am getting stackOverflow error. I am using native datatypes in the class and a Firebase reference object.
The database structure I am using is as follows:
I have created Model Class for Orders as follows:
public class Orders {
private String billNo;
private String custId;
private String dateAndTime;
private int personCount;
private int status;
private int table;
private String orderId;
private boolean AC=true;
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
public String getDateAndTime() {
return dateAndTime;
}
public void setDateAndTime(String dateAndTime) {
this.dateAndTime = dateAndTime;
}
public int getPersonCount() {
return personCount;
}
public void setPersonCount(int personCount) {
this.personCount = personCount;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getTable() {
return table;
}
public void setTable(int table) {
this.table = table;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
public Orders(String orderId, String billNum, String customerId, String date, int personCnt, int status, int tableNo, boolean AC){
this.billNo = billNum;
this.custId = customerId;
this.dateAndTime = date;
this.personCount = personCnt;
this.status = status;
this.table = tableNo;
this.orderId= orderId;
Log.v("Orders","I am in Orders");
}
public Orders(){
}
public void pushOrder(){
Log.v("PushOrdersId",this.getOrderId());
String OId = this.getOrderId();
mDatabase.child("Orders").child(OId).setValue(Orders.this);
}
}
Then I have created its child class Items as follows:
public class Items extends Orders {
private String itemId;
private int qty;
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Orders");
public Items(String orderId, String billNum, String customerId, String date, int personCnt, int status, int tableNo, boolean AC) {
super(orderId, billNum, customerId, date, personCnt, status, tableNo, AC);
// this.itemId = itemId;
// this.qty = qty;
Log.v("Items","I am in Items child");
}
public Items() {
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
// public void push(HashMap<String, Items> items){
// for (Items item: items.values()) {
// String itemKey = mRef.child(this.getOrderId()).child("items").push().getKey();
//
// mRef.child(this.getOrderId()).child("items").child(itemKey).setValue(item);
// }
// }
}
And then I am calling a function PushOrders from Class Orders in another class:
nm=name.getText().toString();
mob=mobile.getText().toString();
seat=seats.getText().toString();
email=emailID.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference("Orders");
String orderTd = mDatabase.push().getKey();
custId = id;
itemsHashMap = new HashMap<>();
// itemsArrayMap.put("itemid","1");
// itemsArrayMap.put("quantity","2");
dateAndTime = new Date();
personCount=Integer.parseInt(seat);
//Toast.makeText(getApplicationContext(), orderTd, Toast.LENGTH_LONG).show();
Items item = new Items(orderTd,billNo, custId, dateAndTime.toString(), personCount, status, table, AC);
item.pushOrder();
// item.push(itemsHashMap);
}
I was able to figure out the following line in class Orders is giving the error, but couldn't figure out why? and how to resolve it.
mDatabase.child("Orders").child(OId).setValue(Orders.this);
Error log
10-05 09:37:34.239 28265-28265/dyncardview.abpss.com E/AndroidRuntime: FATAL EXCEPTION: main Process: dyncardview.abpss.com, PID: 28265 java.lang.StackOverflowError: stack size 8MB at java.lang.reflect.Method.invoke(Native Method) at com.google.android.gms.internal.zzbqi$zza.zzaF
Can anyone please help me out in this case?
I have made some changes in your code according to your firebase DB Structure,
//Set order data
Orders orders=new Orders();
orders.setBillNo("123");
orders.setCustId("12");
orders.setDateAndTime(new Date().toString());
orders.setPersonCount(13);
orders.setStatus(2);
orders.setTable(2);
orders.setOrderId("23");
orders.setAC(true);
//Add items to order
List<Items> itemsList=new ArrayList<Items>();
for(int i=0;i<2;i++){
Items items=new Items();
items.setItemId("55");
items.setQty(i);
itemsList.add(items);
}
orders.setItems(itemsList);
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Orders");
mRef.push().setValue(orders);
Your Order class
public class Orders {
private String billNo;
private String custId;
private String dateAndTime;
private int personCount;
private int status;
private int table;
private String orderId;
private boolean AC = true;
private List<Items> items;
//Generate getter and setters other code
}
Item Class
public class Items {
private String itemId;
private int qty;
//Generate getter and setters other code
}
You can fetch order using order key with complete items (You will get complete item list inside your order)
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Orders").child(yourOrderKey);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot:dataSnapshot.getChildren()) {
Orders orders=postSnapshot.getValue(Orders.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
After creating an Instance of Firebase DB you just have to write the code snippet below:
User users = new User(userID, name, edtEmail.getText().toString().trim(), edtContactNumber.getText().toString().trim());
//saving data onto database
mDatabase.child("user").child(userID).setValue(users);
You can change the model and data as per requirement