Stranger B.
Stranger B.

Reputation: 9364

How can i check if a value exists already in a Parse data class Android

I'm looking for a way on how can I check if a phone number exists already in Parse data class in Android.

For example, checking if a phone number exists already, if yes it returns true if not false.

I used this :

query1.whereEqualTo("phone", "0644444444");
query1.findInBackground(new FindCallback<ParseObject>() {

and it doesn't help much.

Upvotes: 4

Views: 7202

Answers (3)

SavageKing
SavageKing

Reputation: 544

Use getFirstInBackground() in the query and then simply check to see if there is a ParseException.OBJECT_NOT_FOUND exception. If there is, then the object doesn't exist, otherwise it is there! Using getFirstInBackground is better than findInBackground since getFirstInBackground only checks and returns 1 object, whereas findInBackground may have to query MANY objects.

Example

query1.whereEqualTo("phone", "0644444444");
query1.getFirstInBackground(new GetCallback<ParseObject>() 
{
  public void done(ParseObject object, ParseException e) 
  {
    if(e == null)
    {
     //object exists
    }
    else
    {
      if(e.getCode() == ParseException.OBJECT_NOT_FOUND)
      {
       //object doesn't exist
      }
      else
      {
      //unknown error, debug
      }
     }
  }
});

Upvotes: 9

mszaro
mszaro

Reputation: 1372

In general, these Parse callbacks pass you a ParseException and you can check the status code on the exception.

query1.findInBackground(new FindCallback<ParseObject>() {
    public void done(List<ParseObject> objects, ParseException ex) {
       if(ex != null) {
             final int statusCode = ex.getCode();
             if (statusCode == ParsseException.OBJECT_NOT_FOUND) {
                  // Object did not exist on the parse backend
             }
        }
        else {
          // No exception means the object exists
       }
    }
}

There are a bunch of other more specific error code you can find out of getCode, here's the full list on Parse's docs. A few types of data have specific codes, for example when dealing with signup/login there are specific codes for EMAIL_NOT_FOUND.

Upvotes: 0

Andre Perkins
Andre Perkins

Reputation: 7800

Can you try something like this:

    ParseQuery<ParseObject> query = ParseQuery.getQuery(PARSE_CLASS_NAME);// put name of your Parse class here
    query.whereEqualTo("phoneList", "0644444444");
    query.findInBackground(new FindCallback<ParseObject>() {
    public void done(List<ParseObject> phoneList, ParseException e) {
        if (e == null) {
            handleIsUserNumberFound(! phoneList.isEmpty())
        } else {
            Log.d("error while retrieving phone number", "Error: " + e.getMessage());
        }
    }
});

public class handleIsUserNumberFound(boolean isUserNumberFound){
    //do whatever you need to with the value
}

Upvotes: 0

Related Questions