Android - Killing a child in firebase database kills my app - android

In my app, I'm storing a list of data for each user with this ConnectionInformation.java.
package trickandroid.fulllogin;
/**
* Created by Simon Peter on 19-May-17.
*/
public class ConnectionInformation {
String due, selectArea, connectionNum, doorNum, conName, phoneNum, aadharNum, rationNum;
public ConnectionInformation(){
}
public ConnectionInformation(String due, String selectArea, String connectionNum, String doorNum, String conName, String phoneNum, String aadharNum, String rationNum) {
this.connectionNum = connectionNum;
this.doorNum = doorNum;
this.conName = conName;
this.phoneNum = phoneNum;
this.aadharNum = aadharNum;
this.rationNum = rationNum;
this.selectArea = selectArea;
this.due = due;
}
public String getDue() {
return due;
}
public void setDue(String due) {
this.due = due;
}
public String getSelectArea() {
return selectArea;
}
public void setSelectArea(String selectArea) {
this.selectArea = selectArea;
}
public String getConnectionNum() {
return connectionNum;
}
public void setConnectionNum(String connectionNum) {
this.connectionNum = connectionNum;
}
public String getDoorNum() {
return doorNum;
}
public void setDoorNum(String doorNum) {
this.doorNum = doorNum;
}
public String getConName() {
return conName;
}
public void setConName(String conName) {
this.conName = conName;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getAadharNum() {
return aadharNum;
}
public void setAadharNum(String aadharNum) {
this.aadharNum = aadharNum;
}
public String getRationNum() {
return rationNum;
}
public void setRationNum(String rationNum) {
this.rationNum = rationNum;
}
}
Adding data to the firebase works very fine. This is my database structure.
This is my showData() method where .getDoorNum() is called to display it on the ListView.
private void showData(DataSnapshot dataSnapshot) {
if (expandableListView.getVisibility()==View.VISIBLE) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ConnectionInformation cInfo = new ConnectionInformation();
cInfo.setDoorNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getDoorNum());
cInfo.setPhoneNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getPhoneNum());
cInfo.setAadharNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getAadharNum());
cInfo.setRationNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getRationNum());
ArrayList<String> users = new ArrayList<>();
users.add(cInfo.getDoorNum());
users.add(cInfo.getPhoneNum());
users.add(cInfo.getAadharNum());
users.add(cInfo.getRationNum());
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, users);
expandableListView.setAdapter(adapter);
}
}
}
I use this code for deleting the child.
disBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mdata.child(oldArea).child(key).removeValue();
connection.child(oldArea).child(key).removeValue();
toast("Connection Number " + oldNum + " Disconnected Successfully");
startActivity(new Intent(DisconnectActivity.this,AreaGridActivity.class));
}
});
The code works fine in the database but my app crashes with this error...
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String trickandroid.fulllogin.ConnectionInformation.getDoorNum()' on a null object reference
at trickandroid.fulllogin.DetailsActivity.showData(DetailsActivity.java:449)
at trickandroid.fulllogin.DetailsActivity.access$100(DetailsActivity.java:33)
at trickandroid.fulllogin.DetailsActivity$3.onDataChange(DetailsActivity.java:129)
at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
https://gist.github.com/SimonPeter1909/d70be328dd6d9b099a8a96454922432fDetailsActivity.java
I have tried many ways but I can't pass the error...

The situation here is that you have a ValueEventListener which is triggered once when the listener is added, and then again any time the data changes. The listener is explicitly expecting to find an entry with a certain areaName and key.
This is fine the first time the listener runs, but then on button click you delete the entry with that areaName and key. This triggers the listener again(you changed the data), the listener tries to do something with the entry at that areaName and key, it doesn't exist, you get a NullPointerException.
There are a number of ways to avoid this, but you probably need to rethink the flow and exactly what you want to happen.
A quick fix here could be to try checking if the entry is there before trying to use it:
if(ds.child(userID).child("Connection Detail").child(areaName).child(key).exists()) {
ConnectionInformation cInfo = new ConnectionInformation();
cInfo.setDoorNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getDoorNum());
cInfo.setPhoneNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getPhoneNum());
...
...
} else {
//that entry doesn't exist, do something else
}

not enough info, but i think you are callig getDoorNum, when there is no string in there . try
if (!yourmodelclassobject.getDoorNum()==null)
{
//then print your value or whatever is that you do}
or please post little more info

Related

Firebase Can't convert object of type java.lang.String to type

I'm creating a simple library app where books can be added and a list of books can be viewed.
here is my book class
public class Book {
private int _id;
private String _bookTitle;
private String _bookAuthor;
private int _bookISBN;
private Map<String, Object> mp;
public Book() {
}
public Book(String _bookTitle, String _bookAuthor, int _bookISBN) {
this._id = _id;
this._bookTitle = _bookTitle;
this._bookAuthor = _bookAuthor;
this._bookISBN = _bookISBN;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_bookTitle() {
return _bookTitle;
}
public void set_bookTitle(String _bookTitle) {
this._bookTitle = _bookTitle;
}
public String get_bookAuthor() {
return _bookAuthor;
}
public void set_bookAuthor(String _bookAuthor) {
this._bookAuthor = _bookAuthor;
}
public int get_bookISBN() {
return _bookISBN;
}
public void set_bookISBN(int _bookISBN) {
this._bookISBN = _bookISBN;
}
public Map<String, Object> toMap() {
mp = new HashMap<>();
mp.put("bookTitle", this._bookTitle);
mp.put("bookAuthor", this._bookAuthor);
mp.put("bookISBN", this._bookISBN);
return mp;
} }
and here is where I am trying to read from the values which are already written into firebase
public class ViewBook extends AppCompatActivity {
ArrayList<String> myArrayList = new ArrayList<>();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
// DatabaseReference mPostReference = ref.child("books");
DatabaseReference temp = ref.child("books");
ArrayAdapter<String> adapter;
#Override
public void onStart(){
super.onStart();
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Book book = postSnapshot.getValue(Book.class);
myArrayList.add(book.get_bookTitle() + "\n" + book.get_bookAuthor() + "\n" + book.get_bookISBN());
}
ListView lv = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<String>(ViewBook.this, android.R.layout.simple_list_item_1, myArrayList);
lv.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Getting Post failed, log a message
Log.w("VIEWBOOKS", "loadPost:onCancelled", databaseError.toException());
}
};
temp.addValueEventListener(postListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_book);
}}
the error I am getting is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.taylorcampos.androidfirebasedatabase, PID: 25339
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.taylorcampos.androidfirebasedatabase.Book
at com.google.android.gms.internal.zzbtg.zze(Unknown Source)
at com.google.android.gms.internal.zzbtg.zzb(Unknown Source)
at com.google.android.gms.internal.zzbtg.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.example.taylorcampos.androidfirebasedatabase.ViewBook$1.onDataChange(ViewBook.java:38)
at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
at com.google.android.gms.internal.zzbqx.zzZT(Unknown Source)
at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Someone please explain why this is happening and how I could get the list view to list these books that have been put into firebase.
dataSnapshot.getChildren() is going to return you a list of attributes for a book, not a Book object itself. One of those is a String, thus the error
You need another level of data in the database, or if all you're storing is a list of books, remove child("books") and use a generated unique key instead of the string "books"
Additionally, Firebase is going to try to set your fields using camelCase methods and variables (like those in the database), not underscores like those in your Java class. In other words, they should match
Your code:
DatabaseReference ref = database.getReference();
DatabaseReference temp = ref.child("books");
Updated code with correction to solve error:
DatabaseReference ref = database.getReference();
DatabaseReference temp = ref.child("books").toString();
Your doing it wrong this is how you get it
databasereference reference = FirebaseDatabase.getInstance().getReference("books")
if you have a child on that then just add
.child( "like fuser.getUid() something like this" )
once that's done then add a Listener for it, now go to onDataChange add your code like this
String userName = snapshot.child("Data Name").getValue().toString();

returning 2 json values from firebase but one of them is always null? Why?

I'm not an experienced android app developer this only my first app, with that said here is my problem. I am taking the value of "company_name" from the manager's Json area by calling the dataSnapshot from addListenerForSingleValueEvent and than putting the value into the the recipient's Json area(I'm also storing the manager's id "manager_id" in the recipient's Json area), so far that works OK. The problem now is reading the value "company_name" from the recipient's area to populate it in a list using firebaseUI, for some rason I can't figure out why "manager_id" is returned as as a string but "company_name" is null. Here is the code:
Getting the value for the "company_name":
mManagersCompany.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
companyName = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Storing it in the recipient's area:
Map<String, Object> info = new HashMap<>();
info.put("company_name", companyName);
info.put("manager_id", manager_id);
mListOfManagers.push().updateChildren(info);
object:
public class CompanyItem {
private String company_name;
private String manager_id;
public CompanyItem(){}
public CompanyItem(String company_name, String manager_id){
this.company_name = company_name;
this.manager_id = manager_id;
}
public String getCompanyName() {
return company_name;
}
public void setCompanyName(String companyName) {
this.company_name = companyName;
}
public String getManager_id() {
return manager_id;
}
public void setManager_id(String manager_id_entering) {
this.manager_id = manager_id_entering;
}
}
retrieve "manager_id" and "company_name" with populateViewHolder of firebaseUI:
#Override
protected void populateViewHolder(CompanyViewHolder viewHolder, CompanyItem model, int position) {
viewHolder.hText.setText(model.getCompanyName());
viewHolder.mText.setText(model.getManager_id());
}
Here is part of the recipient's Json in firebase database:
{ "-KYVoYBRD4UEBL6GYKD_" :
{
"company_name" : "Dude Company",
"manager_id" : "a1b2c3d4"
}
}
Why does it return "a1b2c3d4" for the "manager_id" but null for "company_name"? I tried so many different things but I wasn't successful, and I searched through stackoverflow for an answer but couldn't find one that is close to my problem. Can anyone help please?
As per my comment
change your setter/getter for company_name to match the format of manager_id –
for example
getCompanyName() to getCompany_name()

NullPointer on Firebase String Item

I am testing Firebase on two items. I am hoping to update a recyclerview to add an item, with the firebase onChildAdded() listener prompting the recyclerview to update. Here is the code where I write to Firebase:
mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: Need to determine if this is proper epoch - i.e. does it account for time zones
Calendar c = Calendar.getInstance();
final String epochTime = String.valueOf(c.getTimeInMillis());
//TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
//check if image has been loaded first
if (resultImageURL != null){
mBaseRef.child("Polls").child(epochTime).child("Image_URL").setValue(resultImageURL);
} else {
Toast.makeText(getApplicationContext(),getResources().getString(R.string.no_image_selected),Toast.LENGTH_LONG).show();
return;
}
//Add Answer Counter defaulted to 0
Map<String, Object> pollAnswerCounter = new HashMap<String, Object>();
pollAnswerCounter.put("Vote_Count", 0);
mBaseRef.child("Polls").child(epochTime).updateChildren(pollAnswerCounter);
//Add Question
Map<String, Object> pollQuestion = new HashMap<String, Object>();
pollQuestion.put("Question", mCreatePollQuestion.getText().toString());
mBaseRef.child("Polls").child(epochTime).updateChildren(pollQuestion);
if (mNumberOfPollAnswersCreatedByUser > 5){
Toast.makeText(getApplicationContext(),getResources().getText(R.string.poll_answers_greater_than_five),Toast.LENGTH_LONG).show();
mNumberOfPollAnswersCreatedByUser = 5;
}
//add answers to Firebase
for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++){
EditText editText = (EditText) mEditTextAnswerLayout.findViewWithTag(getResources().getString(R.string.created_answer_editText_id)+String.valueOf(i+1));
String editTextInputForAnswer = String.valueOf(editText.getText());
final String answerLabel = "Answer";
Map<String, Object> answerChoice = new HashMap<String, Object>();
answerChoice.put(answerLabel, editTextInputForAnswer);
mBaseRef.child("Polls").child(epochTime).child("Answers").child(String.valueOf(i+1)).updateChildren(pollAnswerCounter);
mBaseRef.child("Polls").child(epochTime).child("Answers").child(String.valueOf(i+1)).updateChildren(answerChoice);
Toast.makeText(getApplicationContext(),editTextInputForAnswer,Toast.LENGTH_SHORT).show();
}
Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
toHomeActivity.putExtra("viewpager_position", 2);
startActivity(toHomeActivity);
}
});
Here is the code, in a separate fragment, that I use to retrieve the data from Firebase:
#Override
public void onStart() {
super.onStart();
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String newPollEpoch = dataSnapshot.getKey();
Log.v("Child_Added", "The new child is " + newPollEpoch);
String newPollImageURL = dataSnapshot.child(IMAGE_URL).getValue().toString();
String newPollQuestion = dataSnapshot.child(QUESTION_STRING).getValue().toString();
mNewPollsAray.add(0, new Poll(newPollQuestion, newPollImageURL, newPollEpoch));
mNewPollsAdapter.notifyDataSetChanged();
}
#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) {
}
};
mPollsRef.addChildEventListener(mChildEventListener);
}
#Override
public void onStop() {
super.onStop();
mPollsRef.removeEventListener(mChildEventListener);
}
And here is the error. It is quite odd, as the error is prompting on the "String newPollQuestion." I use the exact same method to write the "newPollImageURL" to Firebase, and that object is not null. Also, there are 2 devices, A and B. A creates and writes the item to Firebase, and then reads it fine. B is the device that is displaying the following:
12-03 16:21:20.255 21043-21043/com.troychuinard.fanpolls E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.troychuinard.fanpolls, PID: 21043
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.troychuinard.fanpolls.Fragment.NewFragment$1.onChildAdded(NewFragment.java:159)
at com.google.android.gms.internal.zzaip.zza(Unknown Source)
at com.google.android.gms.internal.zzakp.zzcxi(Unknown Source)
at com.google.android.gms.internal.zzaks$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
--------- beginning of system
I do not understand why, but changing:
String newPollQuestion = dataSnapshot.child(QUESTION_STRING).getValue.toString;
to:
String newPollQuestion = dataSnapshot.child(QUESTION_STRING).getValue(String.class);
Successfully removed the NullPointer. Any idea why?

Display the ArrayList values into TextVitew

Am working on one android project. i stored the getting response in the ArrayList while parsing from the JsonArray. now i want just display the values to required text views.
Here am doing.
public void updateRedemptionRequestDetails(){
//Dismiss dialog
dlgProgress.dismiss();
// Get the status
String status=redemptionRequestDetailsResponse.getStatus();
if(status.equals("success")){
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = redemptionRequestDetailsResponse.getData();
if(!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0 ){
redemptionRequestDetailsResources.addAll(redemptionRequestDetailsResource);
populateRedemptionDetails(redemptionRequestDetailsResources);
}
}else if ( status.equals("failed")) {
//Show toast based on error code
generalMethods.showToastMessage(context,redemptionRequestDetailsResponse.getErrorcode());
}
}
Can anyone please shed some lights on this.how can i get the values in specified string and display them.
Here my model class
public class RedemptionRequestDetailsResource {
private String rdmId;
private String rdmUniqueBatchTrackingId;
private String rdmLoyaltyId;
private String rdmStatus;
private String rdmCashPaymentStatus;
private String rdmProductCode;
public String getRdmId() {
return rdmId;
}
public void setRdmId(String rdmId) {
this.rdmId = rdmId;
}
public String getRdmUniqueBatchTrackingId() {
return rdmUniqueBatchTrackingId;
}
public void setRdmUniqueBatchTrackingId(String rdmUniqueBatchTrackingId) {
this.rdmUniqueBatchTrackingId = rdmUniqueBatchTrackingId;
}
public String getRdmLoyaltyId() {
return rdmLoyaltyId;
}
public void setRdmLoyaltyId(String rdmLoyaltyId) {
this.rdmLoyaltyId = rdmLoyaltyId;
}
public String getRdmStatus() {
return rdmStatus;
}
public void setRdmStatus(String rdmStatus) {
this.rdmStatus = rdmStatus;
}
public String getRdmCashPaymentStatus() {
return rdmCashPaymentStatus;
}
public void setRdmCashPaymentStatus(String rdmCashPaymentStatus) {
this.rdmCashPaymentStatus = rdmCashPaymentStatus;
}
public String getRdmProductCode() {
return rdmProductCode;
}
public void setRdmProductCode(String rdmProductCode) {
this.rdmProductCode = rdmProductCode;
}
}
here my populateRedemptionDetails method
public void populateRedemptionDetails(List<RedemptionRequestDetailsResource> requestDetailsResource) {
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = requestDetailsResource;
TextView txtLoyaltyId = (TextView)rootView.findViewById(R.id.txtLoyaltyId);
txtLoyaltyId.setText(redemptionRequestDetailsResource.getRdmLoylatyId());
}
i tried like this but it throwing error.
The if condition is wrong, it will never enter:
if (!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0) {
}
it should be:
if (!redemptionRequestDetailsResource.isEmpty()) {}
also, small tip, when using equals, you should put the constant on the left side of the call, like this:
"success".equals(status)
this is to prevent NullPointerExceptions

Add items to a List in Firebase in Android

I am having a hard time trying to figure out how to add more items dynamically to a List in Firebase. As of now I am able to add just one item at the correct firebase location. The user needs to be able to add more items to the list. I am using a custom model class for the data. I would greatly appreciate any help, Thanks.
FloatingActionButton floatSave = (FloatingActionButton) rootView.findViewById(R.id.fabSave);
floatSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFirebaseRef = new Firebase("https://you.firebaseio.com/");
myFirebaseRef = new Firebase("https://you.firebaseio.com/" + "/users/" + myFirebaseRef.getAuth().getUid());
String partyname = partyName.getText().toString();
String when = fromDateEtxt.getText().toString();
String timeOf = fromTimeEtxt.getText().toString();
String userItems1 = addThisItem.getText().toString();
userItems.add(userItems1);
Map<String,Object> values = new HashMap<>();
values.put("partyname", partyname);
values.put("When", when);
values.put("timeOf", timeOf);
values.put("userItems", userItems);
myFirebaseRef.push().setValue(values);
}
});
//Here is how I try to add additional items to the "userItems" List
final Button addItem = (Button) rootView.findViewById(R.id.buttonAddItem);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = pref.edit();
String savedParty = pref.getString("thisPostKey", null);
myFirebaseRef = new Firebase("https://you.firebaseio.com/users/8d5d9915-54d8-4fc1-b92f-b45569e8089b/"+ savedParty + "/userItems");
String additem = addThisItem.getText().toString();
userItems.add(additem);
myFirebaseRef.push().setValue(additem);
System.out.println("There are " + thisKey + savedParty);
}
});
public class PartyPost {
private String partyname;
private String timeOf;
private String when;
private List userItems;
public PartyPost(String partyname, String timeOf, String when, List userItems) {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
this.partyname = partyname;
this.timeOf = timeOf;
this.when = when;
this.userItems = userItems;
}
public void setPartyname(String partyname) {
this.partyname = partyname;
}
public void setTimeOf(String timeOf) {
this.timeOf = timeOf;
}
public void setWhen(String when) {
this.when = when;
}
public void setUserItems(List<String> userItems) {
this.userItems = userItems;
}
public String getPartyname() {
return partyname;
}
public String getTimeOf() {
return timeOf;
}
public String getWhen() {
return when;
}
public List getUserItems() {
return userItems;
}
}
{
"users" : {
"8d5d9915-54d8-4fc1-b92f-b45569e8089b" : {
"-KDcHcfvc3CM-d8TWPE9" : {
"When" : "2-2-2017",
"partyname" : "Super Bowl",
"timeOf" : "5:00PM",
"userItems" : [ "Beer" ]
},
"-KDcHcjRbxXzCvRFa-No" : {
"userItems" : {
"-KDcLXIJ7I9TUFEDyyrA" : "Chips"
}
}
}
}
}
Your /userItems node has child node and per the question it has one child.
"userItems" : {
"-KDcLXIJ7I9TUFEDyyrA" : "Chips"
}
It appears you want to add additional children to that node. To add another child, you will need the path to that specific userItems node, here is pseudo-code
thisUsersUserItemsRef = /users/8d5d9915-54d8-4fc1-b92f-b45569e8089b/-KDcHcjRbxXzCvRFa-No/userItems
then push() the values
values.put("another_user_item", "docs ftw");
thisUsersUserItemsRef.push().setValue(values);
This will result in
"-KDcHcjRbxXzCvRFa-No" : {
"userItems" : {
"-KDcLXIJ7I9TUFEDyyrA" : "Chips",
"-JHoijoiqjodj8jkadiQ" {
"another_user_item": "docs ftw"
}
}
}

Categories

Resources