Calling a parse function asynchronously - android

I have to fetch some data from the parse cloud. I'm using the parse sdk for android. How do I call the method findInBackground asynchronously in my activity? Essentially, where do I place this piece of code in my Activity? Below is my code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Average");
query.whereEqualTo("squarefeet", area);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (int i = 0; i < objects.size(); i++) {
ParseObject p = objects.get(i);
averageConsumption = p
.getNumber("average_consumption");
efficientConsumption = p
.getNumber("efficient_consumption");
}
}
} else {
// something went wrong!
}
}
});

I called it inside an OnClick method of an OnClickListener. This made it asynchronous! Pretty silly but works! Previously I called it synchronously in OnCreate.

Related

Parse Query objects.size always returns 0 Android

public void pictureQuery() {
friendsPic = new ArrayList<>();
for (int i = 0; i < friendsList.length(); i++) {
ParseQuery parseQuery = ParseQuery.getQuery("Data");
parseQuery.whereEqualTo("firstName", "John");
//parseQuery.whereEqualTo("userId",friendsID.get(i));
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
String link = objects.get(0).get("picUrl").toString();
Bitmap bitmap = null;
try {
bitmap = task.execute(link).get();
friendsPic.add(bitmap);
} catch (Exception e1) {
e1.printStackTrace();
}
Log.i("FDA, done", friendsPic.toString());
} else {
Log.i("FD", "0002");
}
} else {
e.printStackTrace();
}
}
});
}
}
Hi guys,
I am trying to retrieve picture URL from parse server (stored as a string), originally I was trying to make a query using the Id, but also tried to hard code it using:
parseQuery.whereEqualTo("firstName", "John");
It always seems to go to the else statement of object.size() > 0 i.e.
Log.i("FD", "0002");
I think i've checked everything including:
size of friendsList ( for the for loop )
spelling, made sure that "Data", "firstName" and "John" are the same on Parse Server
The value of friendsID.get(i)
Tried to use findFirstInBackground instead (same issue)
I have also compared it with my other code for different data ( that works ) :
ParseQuery parseQuery = ParseQuery.getQuery("SportData");
parseQuery.whereEqualTo("id", mApp.getId());
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
saveSportData(objects.get(0), false);
} else if (objects.size() < 1) {
saveSportData(null, true);
}
} else {
e.printStackTrace();
}
}
});
Any idea what am I doing wrong, or what may be causing it ?
Thanks a lot.

android: parse object with null values

i have a query that retrieves a parse objects:
i tried to debug the callback function, and i found that i am getting a correct number of objects but all of their values are null.
allthough there is a value called "state" in which i am getting the values
what am i doing wrong? how do i get the values properly?
final List<Kehila> newKehilas = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Kehila");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e != null) {
Log.e("UNITE", e.toString());
} else {
for (ParseObject k : list) {
Kehila newKehila = new Kehila();
newKehila.setObjectId(k.getString("objectId"));
newKehila.setName(k.getString("name"));
newKehila.setCity(k.getString("city"));
newKehila.setNeighborhood(k.getString("neighborhood"));
newKehila.setStreet(k.getString("street"));
newKehila.setHouseNumber(k.getInt("houseNumber"));
newKehilas.add(newKehila);
}
}
}
});
return newKehilas;
I think you need to call save() or saveEventually() on your new objects.

How to run code sequentially with parse, in Android?

I am trying to get records from parse. My table in parse contains an array of pointers; I was facing difficulties to write parse query, so I first save array of pointers in an ArrayList, now I make a for loop to execute the query; for each loop iteration, I want to get records from parse and update local db then same as for next iterations. But this is creating some different problems. parse getInBackground is not working sequentially.... my outer for loop completely executes then parse method called due to which I am facing problems to save values in local db.
public void insertGroupsInDB(ArrayList<TempGroupClass> temp)
{
Log.d(TAG,"insertGroupsInDB: temp size:"+temp.size());
for(int i = 0;i<temp.size();i++) `//my target is to make inner query run till no of loop times and for each iterations inner parse query will run and then insert records in db against outer insertion group`
{
Groups grp = new Groups();
grp.setGroupTitle(temp.get(i).getGroupTitle());
grp.setGroupType(temp.get(i).getGroupType());
grp.setParseObjectId(temp.get(i).getParseObjectId());
long groupinsert = (YouinDatabase.getInstance(context)).addGroup(grp,context);
//}
/*try
{
final CountDownLatch latch = new CountDownLatch(1);*/
if(groupinsert != -1)
{
//now insert friends
//long friendInsertId = YouinDatabase.getInstance(context).addFriend();
//now get friends from members id
Log.d(TAG,"groups inserted successfully:"+groupinsert);
final ArrayList<Integer> list = new ArrayList<Integer>();
if(temp.get(i).getFriendObjectIdList().size() > 0)
{
for(int j =0;j<temp.get(i).getFriendObjectIdList().size();j++)
{
Log.d(TAG," >>>>>>>>>>>>>>>friend objectId>>>>>>>>>>>>>>:"+temp.get(i).getFriendObjectIdList().get(j));
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContainedIn("objectId",temp.get(i).getFriendObjectIdList());
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> arg0,
ParseException arg1) {
// TODO Auto-generated method stub
if(arg1 == null)
{
//Log.d(TAG,"arg0 size:"+arg0.size());
if(arg0.size() >0)
{
for(int i = 0;i<arg0.size();i++)
{
Log.d(TAG,"arg0.size():"+arg0.size());
Friend f = new Friend();
f.setUsername(arg0.get(0).getString("username"));
f.setParseObjectId(arg0.get(0).getObjectId());
f.setHasAdded(false);
boolean userAlreadyExist = YouinDatabase.getInstance(context).checkUserExistInFriendTable(arg0.get(0).getString("username"));
long friendInsertId = -1;
ArrayList<Integer> list = new ArrayList<Integer>();
int friendid;
if(!userAlreadyExist)
{
// Log.d(TAG,"friend Already not exist :"+userAlreadyExist);
friendInsertId = YouinDatabase.getInstance(context).addFriend(f);
list.add(YouinDatabase.getInstance(context).findFriendIdOfLatestRecord());
friendid = YouinDatabase.getInstance(context).findFriendIdOfLatestRecord();
}
else
{
//Log.d(TAG,"friend Already exist :"+userAlreadyExist);
//list.add(YouinDatabase.getInstance(context).getFriendIdFromFriendName(arg0.get(0).getString("username")));
friendid = YouinDatabase.getInstance(context).getFriendIdFromFriendName(arg0.get(0).getString("username"));
}
// Log.d(TAG,"list size 1 :"+list.size());
int latestGroupInsertId = YouinDatabase.getInstance(context).findGroupIdOfLatestRecord();
long id = YouinDatabase.getInstance(context).addFriendInConnection(friendid,latestGroupInsertId);
//now update user setHasAdded
long updateFriendTable = -1;
if(id != -1)
{
updateFriendTable = YouinDatabase.getInstance(context).updateFriendTable(friendid);
}
Log.d(TAG,">>>>updated friend id information:>>>>");
if(updateFriendTable != -1)
{
Friend friendDetails = YouinDatabase.getInstance(context).getFriendDetailsFromFriendId(friendid);
Log.d(TAG,"friend name:"+friendDetails.getUsername());
Log.d(TAG,"friend:"+friendDetails.getParseObjectId());
Log.d(TAG,"friend added :"+friendDetails.isHasAdded());
Log.d(TAG,"groupId:"+latestGroupInsertId);
}
//YouinDatabase.getInstance(context).get
}
Log.d(TAG,"list size 2"+list.size());
}
}
else
{
Log.d(TAG,"arg1 != null:"+arg1.getMessage());
}
}
});
}
// Log.d(TAG,"list size:"+list.size());
}
//latch.countDown();
}
/*latch.await();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
Right now, the problem is that my outer loop executes twice one after another and then after the loop ends, then my parse method brings data from parse ...due to which it's only updating record in db against last group id ...and it's not inserting records against first groupId
How to resolve this issue? I have used this technique because I failed to write query to get object result of array of pointers using parse.
You could use find() which should do a synchronous operation which might hold up your ui. I have not used parse yet so i dont know. Or you can set up something like below. Remove the outer and check conditions in your callback to determine when to launch the next query.
private int j = 0;
private int loopnumber = temp.size();
ArrayList<TempGroupClass> temp; //setup temp somewhere else
private void doQuery() {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContainedIn("objectId",temp.get(i).getFriendObjectIdList());
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> arg0,
ParseException arg1) {
// TODO Auto-generated method stub
if(arg1 == null)
{
...
...
else
{
Log.d(TAG,"arg1 != null:"+arg1.getMessage());
}
//at the end call the same method to start a query if the loop conditions have not been reached.
if(++i < loopnumber) {
doQuery();
}
}
});
}
}

Android - Parse.com Populating Array from ONE element

I am trying to populate an Array from a parse.com query and I am stock in the part of getting the element from query. basically i dont know where to get the current location for exercise_object.get(location) thanks.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Programs");
query.whereEqualTo("name", objname);
query.orderByAscending("name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
//success
String [] exercice = new String[3];
exercise_object = list;
Toast.makeText(Wko_Display.this, "Workouts", Toast.LENGTH_LONG).show();
ParseObject program_object = exercise_object.get(location);
exercice [0] = exercise_object.getString("wk0");
exercice [1] = exercise_object.getString("wk1");
exercice [2] = exercise_object.getString("wk2");
}
If I understand what you're trying to do correctly, then this should work:
#Override
public void done(List<ParseObject> list, ParseException e){
if (e == null){
for (ParseObject pObj : list){
String[] exercise = new String[3];
// assuming each ParseObject has a pointer to a Program object in the database
ParseObject programObject = pObj.getParseObject("location");
// do whatever you want with this programObject
// then do any further stuff with the current pObj in the list
exercise[0] = pObj.getString("wk0");
// ...
}
} else{
Log.e(TAG, e.getMessage());
}
}
This would be wrong if you're expecting only one object to be returned from the query though. Let me know.

Android: parse query in thread

I'm using the Parse library to query some records from DB that will be shown in a ListView with a custom adapter. I've a table with records and each record should I do a counting query from other table.
This is the thread for the counting query of each object retrieved:
getVisualizations = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < events.size(); i++) {
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstant.PT_VISUALIZ);
query.whereEqualTo(ParseConstant.PT_VISUALIZ_EVENTO, events.get(i));
events.get(i).setVisualizations(query.count());
}
}
});
events is an Object ArrayList
And this is the code in the main
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstant.PT_EVENT);
query.setLimit(30);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> resultList, ParseException e) {
if (e == null) {
events = new ArrayList<Event>();
for (int i = 0; i < resultList.size(); i++) {
Event event = (Event) resultList.get(i);
events.add(event);
}
if (!getVisualizations.isAlive()) {
getVisualizations.start();
}
if (adapter != null) {
adapter.notifyDataSetChanged();
} else {
adapter = new AdapterEvent(getActivity(), R.layout.list_event, events, list);
AnimationAdapter animAdapter = new SwingBottomInAnimationAdapter(adapter);
animAdapter.setAbsListView(list);
list.setAdapter(animAdapter);
}
loadingBar.setVisibility(View.INVISIBLE);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
The problem is that after the thread has started, I don't know how to block the main thread until the other thread finish. (Sorry for the english :/ )
perhaps you should use Thread.join() - if we are dealing with 2 threads, this will block one thread, while allowing the other to complete, then once it does complete, it will resume. Here is a tutorial on it

Categories

Resources