Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

android - Add an item to a list in Firebase Database

I have the following Firebase database structure. uIds is a type of List<String>. I am trying to add another uId under uIds with an incremented index. setValue() and updateChildren() would require me to retrieve existing data, and push() will add an item with a randomly generated string as a key instead of an incremented index. Is there a simpler way that does not require to retrieve the existing data? Thanks!

  "requests" : {
    "request001" : {
      "interests" : [ "x" ],
      "live" : true,
      "uIds" : [ "user1" ]  // <---- from this
    },
    "request002" : {
      "interests" : [ "y" ],
      "live" : true,
      "uIds" : [ "user2" ]
    }
  }

--------------------------------

Edit:

Sorry for the unclarity. Let me elaborate to make it clear. Say I have the above database and want to update it to the following.

  "requests" : {
    "-KSVYZwUQPfyosiyRVdr" : {
      "interests" : [ "x" ],
      "live" : true,
      "uIds" : [ "user1", "user2" ]   // <--- to this
    },
    "-KSl1L60g0tW5voyv0VU" : {
      "interests" : [ "y" ],
      "live" : true,
      "uIds" : [ "user2" ]
    }
  }

ishmaelMakitla's suggestion, mDatabase.child("requests").child("request001").setValue(newRequest), will overwrite the "request001" with "newRequest". So I should retrieve the existing data of "request001" and add "user2" to the list uIds. It will be something like this:

mDatabase.child("requests").child("request001").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Request newRequest = dataSnapshot.getValue(Request.class);
        newRequest.uIds.add("user2");
        mDatabase.child("requests").child("request001").setValue(newRequest);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}

});

But I am wondering if this process is necessary since what I am trying to do is simply to add one item to the list uIds.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...