Search code examples
javaandroidarraysparse-platformparse-server

Remove a single instance of a String stored in a ParseObject Array List


I'm trying to remove a single instance of a string from an Array field in Parse:

final ParseObject post = mPosts.get(position);
List<String> repliedToByList = post.getList("repliedToBy"); // Retrieve current list
ParseUser currentUser = ParseUser.getCurrentUser().getObjectId();
repliedToByList.remove(currentUserObjectId); // Remove first instance of specified objectid
post.remove("repliedToBy"); // Clear the entire list
post.addAllUnique("repliedToBy", Collections.singletonList(repliedToByList)); // Add the new list

That string is the current user's objectId, which is added when a user replies to a "post", as such:

post.addAll("repliedToBy", Collections.singletonList(ParseUser.getCurrentUser().getObjectId()));

For example, the Array contains:

["1RtqEgy1ct","f4qEWY8UOM","f4qEWY8UOM"]

Is there any way to just remove one single instance of f4qEWY8UOM? The alternative is to do everything using increments/decrements, but that is not ideal for me.


Solution

  • Incrementing my replyCount is easy:

    // Increment replyCount
    postObject.increment("replyCount", 1);
    postObject.saveInBackground();
    

    But there is something wrong with the Android Parse SDK's stated decrement method, i.e. postObject.increment("replyCount", -1), so I tried the following:

    Instead of storing a list of objectIds in a list and then counting its size, I simply increment/decrement in the following way, by always fetching the previous replyCount, subtracting 1, and then saving the new put call:

    // Decrement replyCount
    int newReplyCount = postObject.getInt("replyCount") - 1;
    postObject.put("replyCount", newReplyCount);
    postObject.saveInBackground();