Stephane Maarek
Stephane Maarek

Reputation: 5352

Parse.com - Android: boolean on if a User belongs to an Array

I have an array of Users in a class, under the column "likers" I want to check whether or not the current user is contained in the likers array, in minimal time This is my current (dysfunctional) code:

        ArrayList<ParseUser> likers = (ArrayList<ParseUser>) rating.get("likers");
        Boolean contained = likers.contains(ParseUser.getCurrentUser()) //always returns false

How can I change it to make it work? I feel it's a match on ObjectId. Maybe there is a function in the Parse SDK?

Thanks!

Upvotes: 0

Views: 207

Answers (1)

gio
gio

Reputation: 5020

You can use next approach.

    ParseObject rating = ParseObject.create(ParseObject.class);
    ArrayList<ParseUser> likers = (ArrayList<ParseUser>) rating.get("likers");
    Boolean contained = containsUser(likers, ParseUser.getCurrentUser());

Method

private boolean containsUser(List<ParseUser> list, ParseUser user) {
    for (ParseUser parseUser : list) {
        if (parseUser.hasSameId(user)) return true;
    }
    return false;

}

Little bit about your code. It works correct, return false. Because ArrayList implements the List Interface. If you look at the Javadoc for List at the contains method you will see that it uses the equals() method to evaluate if two objects are the same. Result of rating.get("likers") contains same ParseUsers as ParseUser.getCurrentUser, but they are different objects at memory. So you need find it by comparing ObjectId from Parse.com.

Upvotes: 2

Related Questions