I am using Parse.com
as a backend for my app. They also offer a local database to store information, as an alternative to SQLite
.
I want to add numbers from phone to my database with parse. Before adding a number I need to check if the number already exists in the database, so I use findInBackground()
to get a list of numbers that match the number I want to add. If the list is empty the number I want to add doesn't exists in the database.
The method to do this is:
public void putPerson(final String name, final String phoneNumber, final boolean isFav) {
// Verify if there is any person with the same phone number
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseClass.PERSON_CLASS);
query.whereEqualTo(ParseKey.PERSON_PHONE_NUMBER_KEY, phoneNumber);
query.fromLocalDatastore();
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> personList,
ParseException e) {
if (e == null) {
if (personList.isEmpty()) {
// If there is not any person with the same phone number add person
ParseObject person = new ParseObject(ParseClass.PERSON_CLASS);
person.put(ParseKey.PERSON_NAME_KEY, name);
person.put(ParseKey.PERSON_PHONE_NUMBER_KEY, phoneNumber);
person.put(ParseKey.PERSON_FAVORITE_KEY, isFav);
person.pinInBackground();
Log.d(TAG,"Person:"+phoneNumber+" was added.");
} else {
Log.d(TAG, "Warning: " + "Person with the number " + phoneNumber + " already exists.");
}
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
}
);
}
Then I call this method 3 times to add 3 numbers:
ParseLocalDataStore.getInstance().putPerson("Jack", "0741234567", false);
ParseLocalDataStore.getInstance().putPerson("John", "0747654321", false);
ParseLocalDataStore.getInstance().putPerson("Jack", "0741234567", false);
ParseLocalDataStore.getInstance().getPerson(); // Get all persons from database
Notice that the third number is the same as the first, and it shouldn't be added to database. But the logcat
shows:
12-26 15:37:55.424 16408-16408/D/MGParseLocalDataStore: Person:0741234567 was added.
12-26 15:37:55.424 16408-16408/D/MGParseLocalDataStore: Person:0747654321 was added.
12-26 15:37:55.484 16408-16408/D/MGParseLocalDataStore: Person:0741234567 was added.
The third number was added even if it wasn't supposed to do this, because fintInBackground()
is running in 3 background threads almost simultaneously, so it will find that there is no number in the database like the one I want to add.
In this question a guy told me that I should use Bolts
library from Parse
. I read about it from here and some Parse
blog posts, but I don't fully understand how to use this with the method I already have, and how to syncronize the queries to be executed one after another.
If someone worked with this library please guide me on how to do this or provide some basic examples so I can understand the workflow.
Thanks!