Firebase Android How to push data from Model class itself - android

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

Related

list cannot be applied to boolean android

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);

How to create an array list inside a realm object for todo app?

I want to develop todo app with the realm database. I have successfully created a list and displayed in recycler view. but when I try to add task inside the recycler view item. I'm a little bit confused. I don't know how to achieve this.
for example:
this is my POJO class
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ShoppingModel extends RealmObject {
#PrimaryKey
private int id;
private String title;
private String items;
private String color;
private String date;
private String time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getItems() {
return items;
}
public void setItems(String items) {
this.items = items;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
This is my realm helper class
import android.util.Log;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
public class RealmHelper {
Realm realm;
public RealmHelper(Realm realm){
this.realm = realm;
}
//save data to realm
public void save(final ShoppingModel shoppingModel){
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
if (realm!=null){
Log.e("Log", "Database was created " );
Number currentID = realm.where(ShoppingModel.class).max("id");
int nextId;
if (currentID == null){
nextId=1;
} else {
nextId = currentID.intValue() + 1;
}
shoppingModel.setId(nextId);
ShoppingModel s = realm.copyToRealm(shoppingModel);
} else {
Log.e("Log", "Database not exits " );
}
}
});
}
public List<ShoppingModel> getAllShoppingList(){
RealmResults<ShoppingModel> shopResult = realm.where(ShoppingModel.class).findAll();
return shopResult;
}
//update data to realm
public void update(final int id, final String title, final String items, final String color, final String date, final String time){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ShoppingModel shoppingModel = realm.where(ShoppingModel.class).equalTo("id",id)
.findFirst();
shoppingModel.setTitle(title);
shoppingModel.setItems(items);
shoppingModel.setTime(time);
shoppingModel.setDate(date);
shoppingModel.setColor(color);
}
}, new Realm.Transaction.OnSuccess(){
#Override
public void onSuccess() {
}
}, new Realm.Transaction.OnError(){
#Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
}
// delete from realm
public void delete(final int id, final String title, final String items, final String color, final String date, final String time){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ShoppingModel shoppingModel = realm.where(ShoppingModel.class).equalTo("id",id)
.findFirst();
shoppingModel.setTitle(title);
shoppingModel.setItems(items);
shoppingModel.setTime(time);
shoppingModel.setDate(date);
shoppingModel.setColor(color);
shoppingModel.deleteFromRealm();
realm.commitTransaction();
}
}, new Realm.Transaction.OnSuccess(){
#Override
public void onSuccess() {
}
}, new Realm.Transaction.OnError(){
#Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
}
}
Here's my output
Now I want to click that item inside that item i want to add task with checkbox
for example like this
Both List and ShoppingModel cannot be stored in Realm directly. You will need to create a model object for ShoppingModel and then use a RealmList object containing your model objects.
public class ShoppingModel extends RealmObject {
public ShoppingModel() { }
#PrimaryKey
private int id;
private String title;
private String items;
private String color;
private String date;
private String time;
RealmList<ShoppingModelDetails> shoppingListDetails = new RealmList<ShoppingModelDetails>();
// getter setters are here.
}
ShoppingModelDetails class is here -
public class ShoppingModelDetails extends RealmObject {
public ShoppingModelDetails() { }
#PrimaryKey
private int id;
private String title;
private String items;
private String color;
private String date;
private String time;
// getter setters are here.
}
//Add shopping model details objects to shoppingListDetails and store it in your ShoppingList object
You will need to manually convert objects of the ShoppingModelDetails class to the ShoppingModel class when you are inserting/retrieving from the database.

Another List inside my Custom Listview with Firebase

I'm trying to display another list inside my custom listview like in the image below. I have successfully display the first three child(name, sport and town). But when i add the coverage child i got this error 'failed to convert value of type arraylist to string' in main activity.
Error message
Failed to convert value of type java.util.ArrayList to String
This is the display im trying to achieve
This is what im trying to achieve
This is my firebase database structure
db structure
I got this code below for my main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView)findViewById(R.id.cusListView);
mTextView = (TextView)findViewById(R.id.textV);
mRef = FirebaseDatabase.getInstance().getReference().child("Person");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot){
ArrayList<PeopleGetSet> array = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
PeopleGetSet arr = ds.getValue(PeopleGetSet.class);
array.add(arr);
ViewDatabase adapter = new ViewDatabase(this, R.layout.adapter_view_layout, array);
mListView.setAdapter(adapter);
}
}
This it my code for Adapter
public class ViewDatabase extends ArrayAdapter<PeopleGetSet> {
private static final String TAG="ViewDatabase";
private Context mContext;
int mResource;
public ViewDatabase(#NonNull Context context, int resource, #NonNull List<PeopleGetSet> objects) {
super(context, resource, objects);
this.mContext=context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String name =getItem(position).getName();
String sport =getItem(position).getSport();
String town =getItem(position).getTown();
String Coverage =getItem(position).getCoverage();
PeopleGetSet person = new PeopleGetSet(name,sport, town, Coverage);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource, parent, false);
TextView tvName = (TextView)convertView.findViewById(R.id.textView);
TextView tvSport = (TextView)convertView.findViewById(R.id.textView2);
TextView tvTown = (TextView)convertView.findViewById(R.id.textView3);
TextView tvCoverage = (TextView)convertView.findViewById(R.id.textView4);
tvName.setText(name);
tvSport.setText(sport);
tvTown.setText(town);
tvCoverage.setText(Coverage);
return convertView;
}
}
And this is my code for Getter and setter
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private String Coverage;
public PeopleGetSet() {
}
public PeopleGetSet(String name, String sport, String town, String Coverage) {
this.name = name;
this.sport = sport;
this.town = town;
this.Coverage = Coverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getCoverage() {
return Coverage;
}
public void setCoverage(String coverage) {
Coverage = coverage;
}
}
I mean like this:
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private Coverage coverage;
... default code
}
public class Coverage {
private ArrayList<String> names;
... default code
}
Problem is in your Getter Setter class Add Coverage as Hashmap in your PeopleGetSet class. Coverage is not string its array so to read array from firebase you should use HashMap
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private HashMap<String,String> Coverage ;
public PeopleGetSet() {
}
public PeopleGetSet(String name, String sport, String town, HashMap<String, String> Coverage) {
this.name = name;
this.sport = sport;
this.town = town;
this.Coverage = Coverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getTown() {
return town;
}
public HashMap<String,String> getCoverage() {
return Coverage;
}
There is a simple way to inflate multiple views inside one ListView. Here's my example code.
public class MyExampleCode extends ArrayAdapter<Object> {
private static final int TYPE_1 = 0;
private static final int TYPE_2 = 1;
private Context context;
private List<Object> objectList;
public MyExampleCode(Context context, List<Object> objectList) {
super(context,layout,objectList);
this.context = context;
this.objectList = objectList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (getItemViewType(position) == TYPE_1) {
PeopleGetSet peopleGetSet = (PeopleGetSet)objectList.get(position);
//handle code for first object, inflate layout and fill it
} else {
Coverage coverage = (Coverage)objectList.get(position);
//handle code for second object, inflate layout and fill it
}
}
#Override
public int getItemViewType(int position) {
if (getItem(position) instanceof PeopleGetSet) {
return TYPE_1;
} else {
return TYPE_2;
}
}
#Nullable
#Override
public Object getItem(int position) {
return objectList.get(position);
}
#Override
public int getCount() {
return objectList.size();
}
}
#Edit
Let update your code
private void showData(DataSnapshot dataSnapshot){
List<Object> array = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
PeopleGetSet arr = ds.getValue(PeopleGetSet.class);
Coverage arr2 = arr.getCoverage();
array.add(arr);
array.add(arr2);
}
ViewDatabase adapter = new ViewDatabase(this, array);
mListView.setAdapter(adapter);
}

unable to retrieve data from one app to another app from firebase single Database

I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");

To get sum of all child entries of Firebase

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()));
}

Categories

Resources