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);
Related
DataBase Structure
I am trying to get reference to Users from Chatlist. What i am trying to do is if a users is logged in he will see the users mentioned under is Uid in Chatlist node inside his recyclerview.
I am getting a the nullpointerexception in the following line
DatabaseReference UserRef = rootRef.child("Users").child(chatlist.getId());
Exception
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(com.google.firebase:firebase-database##19.2.1:96)
at com.shivam.chatapp2.Fragments.Chats.onCreateView(Chats.java:112)
MyCode
public class Chats extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
FirebaseUser fuser;
DatabaseReference reference;
FloatingActionButton profile, credentials;
ValueEventListener ChatListListener;
List<Chatlist> usersList;
private ChatsFragmentAdapter chatsFragmentAdapter;
public Chats() {
// 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_chats, container, false);
profile = view.findViewById(R.id.fab_edit_profile_pic);
credentials = view.findViewById(R.id.fab_edit_name);
FabAction();
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fuser = FirebaseAuth.getInstance().getCurrentUser();
usersList = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chatlist chatlist = snapshot.getValue(Chatlist.class);
usersList.add(chatlist);
}
}
//chatList();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Chatlist chatlist=new Chatlist();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserRef = rootRef.child("Users").child(chatlist.getId());
UserRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter = new UserAdapter(getContext(), mUsers, true);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
Update
Chatlist.java
public class Chatlist {
public String id;
public String MessageCheck;
public Chatlist() {
}
public Chatlist(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
User.java
public class User {
private String id;
private String First;
private String EmailID;
private String imageURL;
private String status;
public User(String id, String first, String emailID, String imageURL,String status) {
this.id = id;
this.First = first;
this.EmailID = emailID;
this.imageURL = imageURL;
this.status=status;
}
public User() {
}
public User(String userid, String first_name, String eMail) {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getEmailID() {
return EmailID;
}
public void setEmailID(String emailID) {
EmailID = emailID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
start listening to the users node from your first query of chatlist node:
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chatlist chatlist = snapshot.getValue(Chatlist.class);
usersList.add(chatlist);
//start listening to users node here
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserRef = rootRef.child("Users").child(chatlist.getId());
UserRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
.....
....
....
}
....
....
update
Make sure this line is removed:
Chatlist chatlist=new Chatlist();
update 2
don't do this inside your users query:
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
instead do this:
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
update 3
chatlist class:
public class Chatlist {
public String id;
public Chatlist(String id) {
this.id = id;
}
public Chatlist(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
users class:
public class User {
private String id;
private String First;
private String EmailId;
private String imageURL;
private String status;
public User(String id, String First, String EmailId, String imageURL,String status) {
this.id = id;
this.First = First;
this.EmailId = EmailId;
this.imageURL = imageURL;
this.status=status;
}
public User() {
}
public User(String userid, String first_name, String eMail) {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
this.First = first;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getEmailID() {
return EmailId;
}
public void setEmailID(String emailID) {
this.EmailId = emailID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
I'm extracting a Boolean from Firebase. However, I'm getting an the Can't convert object of type java.lang.Boolean error when I pull this data.
How do I pull Boolean data?
List<Product> productList;
List<Boolean> productListStates;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
final DatabaseReference ref = mDatabase.child("0").child("states").child("001");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Product p = snapshot.getValue(Product.class);
productListStates.add(p.getStates());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Product Class:
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;
}
}
As I see in your schema, under the states node there is no object of type Product, is only a property of type boolean. That's why you get that error. To solve this, please use the following lines of code:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
final DatabaseReference ref = mDatabase.child("0").child("states").child("001");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
booblean b = snapshot.getValue(Boolean.class);
Log.d(TAG, String.valueOf(b));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
The result in the logcat will be:
true
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()));
}
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
Can anyone help me to retrieve data from every child except doctor_profile.
Do i need to create separate class for every child or there is another way to solve this problem.
TIA
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("addiction psychiatrist");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
Psychiatrist psychiatrist = snapshot.getValue(Psychiatrist.class);
//now you can add it to your list (collection) or do what you want
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and of course you must have class which represents your objects, so for example:
#IgnoreExtraProperties
public class Psychiatrist {
private String name;
private String city;
private String hospital;
public Psychiatrist() {
// required empty constructor
}
public Psychiatrist(String name, String city, String hospital) {
this.name = name;
this.city = city;
this.hospital = hospital;
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
public String getHospital() {
return hospital;
}
}