Reputation: 105
Can someone help me out with a firebase problem I am having, I want to add a child inside another child, I know this is simple, but since I am new to firebase, I will really appreciate any help regarding this, please let me know, if this question needs improvement in formatting, so that I can get better at stack overflow.
Adding item from this function
public void addItem(Item model) {
Item item = new Item();
item.setItem(model.getItem());
item.setPonum(model.getPonum());
item.setQty(model.getQty());
item.setSupplier(model.getSupplier());
item.setContact(model.getContact());
item.setTransporter(model.getTransporter());
item.setLrnum(model.getLrnum());
item.setRemarks(model.getRemarks());
String key = mDatabase.child("Items").push().getKey();
Map<String, Object> postValues = item.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, postValues);
mDatabase.updateChildren(childUpdates);
}
I need exception only for the remarks section, I will upload pics of what exactly I have in mind, below image is what I currently have, I want the database like the second image
Upvotes: 1
Views: 3471
Reputation: 2163
I think your Item
object should look like this:
public class Item {
private String contact;
private String item;
private String lrnum;
private String ponum;
private String qty;
private HashMap<String, String> remarks;
private String supplier;
private String transporter;
// ... you configure setting method by setter or constructor, your choice
public String getContact() {
return contact;
}
public String getItem() {
return item;
}
public String getLrnum() {
return lrnum;
}
public String getPonum() {
return ponum;
}
public String getQty() {
return qty;
}
public HashMap<String, String> getRemarks() {
return remarks;
}
public String getSupplier() {
return supplier;
}
public String getTransporter() {
return transporter;
}
// and maybe add this to easily add one remarks
public void addRemark(String remarkKey, String remark) {
if (remarks == null)
remarks = new HashMap<>();
remarks.put(remarkKey, remark);
}
}
Then you only need this lines of code to insert it into your Firebase database:
public void addItem(Item model) {
mDatabase.child("Items").push().setValue(model);
}
Upvotes: 1
Reputation: 10625
Get a reference of your Node where you have to push new data.
Firebase newRef = ref.child("Key_of_root_node").child("remarks_parent_node").child("remarks").push();
newRef.setValue("Hi I am Comment");
Push will generate key for you, so no need to do handling for generating keys like Comment1, Comment2.
Upvotes: 1