my query.findInBackground not getting executed in android - android

I am using parse for my data in android app. for some reason the code inside query.findInBackground is not getting executed.
public List<Date> sessionHeaderFetch(){
Log.d("test", "session fetch entry");
ParseQuery<Sessions> query = ParseQuery.getQuery(Sessions.class);
final List<Date> sessionHeaders = null;
query.findInBackground(new FindCallback<Sessions>() {
#Override
public void done(List<Sessions> sessionsObjects, com.parse.ParseException e) {
Log.d("test", "session internal entry");
if (e == null) {
Log.d("test", "Retrieved " + sessionsObjects.size() + " sessions");
for (Sessions session : sessionsObjects) {
sessionHeaders.add(session.getNetsDate());
};
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
Log.d("test", "session last value");
return sessionHeaders;
}
the code inside public void done() is not all invoked.

I don't think you have understood how to query correctly in Parse.
When you define the parse query. The get query should contain the name of the table that you are trying to query. Also the queries returned will be ParseObjects normally, so I would expect that your callback should be new FindCallback().
I've adjusted the parse query below.
ParseQuery<Sessions> query = ParseQuery.getQuery("ParseTableName");
final List<Date> sessionHeaders = null;
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> sessionsObjects, com.parse.ParseException e) {
Log.d("test", "session internal entry");
if (e == null) {
// Find succeeded, so do something
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
Obviously you will need to replace "ParseTableName" with the name of the table that you are trying to query in parse.

I actually solved it by using an ArrayList, there were some problems with the List initialization and also the results are fetched asynchronous manner so my functions which calls these functions were getting null values so I had to write by calling functions that calls the parse fetch functions asynchronously as well.
but the query can be written like this and it works.
public void sessionFetch(Date headers, final ParseIOListener<Sessions> listener){
ParseQuery<Sessions> query = ParseQuery.getQuery(Sessions.class);
Log.d("test", "input header" + headers );
query.whereEqualTo("NetsDate",headers);
final ArrayList<Sessions> sessionsData = new ArrayList<Sessions>();
query.findInBackground(new FindCallback<Sessions>() {
#Override
public void done(List<Sessions> sessionsObjects, com.parse.ParseException e) {
if (e == null) {
for (Sessions session : sessionsObjects) {
Log.d("test", "output objects" + session.toString() );
sessionsData.add(session);
Log.d("test", "Retrieved -- sessions" + sessionsObjects.size() );
}
listener.onDataRetrieved(sessionsData);
} else {
listener.onDataRetrieveFail(e);
}
}
});
}
If you want more details on implementing this, check this link

The reason why you feel the code is not being invoked is because you are returning from the method before the ".findInBackground" operation has completed. Remember the query is performed on a background thread. So this is how your code will run:
ParseQuery query = ParseQuery.getQuery(Sessions.class);
final List sessionHeaders = null;
------> 1. query.findInBackground (Popped onto background thread)
return sessionHeaders; (by the time you get here, sessionHeaders will probably still be null).
So change the logic of the code and wait till the callback returns before doing any processing on the "sessionHeaders" object.

Related

Add new row in Parse class using Android

Can't create a new row in using Parse in android. I am able to retrieve, but when I try to add a new row like this, I keep getting false and new row is not being created.
What am I doing wrong here ?
I am exactly following what is given in Parse-Android documentation.
ParseObject storyActivity = new ParseObject("StoryActivity");
storyActivity.put("createdByUser", user);
storyActivity.put("story", story);
storyActivity.put("type", likeUnlike);
return storyActivity.saveInBackground().isCompleted();
Check class level permission Write under class StoryActivity's Security on console.
Call that in following way -
ParseObject storyActivity = new ParseObject("StoryActivity");
storyActivity.put("createdByUser", user);
storyActivity.put("story", story);
storyActivity.put("type", likeUnlike);
storyActivity.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
// your object is successfully created.
} else {
//error occurred
Toast.makeText( context,e.getMessage().toString(),Toast.LENGTH_LONG );
}
}
});
So, by this toast message you can know what is reason of problem you are getting.
Try on this way to set read write permission when user insert/ update record in parse database like ...
ParseObject storyActivity = new ParseObject("StoryActivity");
storyActivity.put("createdByUser", user);
storyActivity.put("story", story);
storyActivity.put("type", likeUnlike);
// here first set read write permission like ..
// when user update value ya insert new value in database
ParseACL postACL = new ParseACL(ParseUser.getCurrentUser());
postACL.setPublicReadAccess(true);
postACL.setPublicWriteAccess(true);
storyActivity.setACL(postACL);
storyActivity.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
// success
} else {
// fail
Log.e("Tag", "getting to fail " + e.getMessage());
}
}
});

Parse Cloud Code weird bug

I have created a parse cloud beforeSave trigger for the predefined class ParseInstallation in order to delete duplicate parse installations for the same user, kinda like what is on this gist. My deployed cloud code is the following:
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.Installation);
//PROBLEM: request.object.get("username") is undefined...
query.equalTo("username", request.object.get("username"));
query.first().then(function(duplicate) {
if (typeof duplicate === "undefined") {
console.log("Duplicate does not exist, New installation");
response.success();
} else {
console.log("Duplicate exist..Trying to delete " + duplicate.id);
duplicate.destroy().then(function(duplicate) {
console.log("Successfully deleted duplicate");
response.success();
}, function() {
console.log(error.code + " " + error.message);
response.success();
});
}
}, function(error) {
console.warn(error.code + error.message);
response.success();
});
})
The problem, as it is commented inline on the code, is that the request.object.get("username") returns undefined. In fact, all the properties of request.object are undefined!
On my android client app I associate the ParseUser and also the username to the ParseInstallation object, as follows:
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("username", username);
installation.put("user", user);
installation.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
Log.e(TAG, "Parse installation was created successfully!");
} else {
Log.e(TAG, "An error occurred while saving Parse installation: " + e.toString());
}
}
});
//more code...
} else {
Log.e(TAG, "Signup error: " + e.getMessage());
//more code...
}
}
});
So, given the above, one would expect that, on the parse cloud, request.object.get("username") would return the actual user username and not undefined, correct??? (Btw, yes I have checked that the username variable on the android client code is not null nor empty!)
Why the hell request.object properties are all undefined???
How to get username from ParseInstallation on the cloud trigger then???
Also, did anyone experienced this problem from an IOS client app?
Retrieve the username through the request.user object:
var User = request.user;
console.log(User.get("username"));
//or skip the first step:
console.log(request.user.get("username"));
Note you can also retrieve these values by calling the attributes property of the Parse.Object (typically bad practice):
console.log(request.user.attributes.username);

table not updating in parse

I am trying to run a function to update some data in an existing table in parse.com. Below is the function:
private void saveMeToDBnCloud(final LocModel aLocObj)
{
db.addLoc(aLocObj);
ParseQuery<ParseObject> query = ParseQuery.getQuery("tblxxx");
query.getInBackground(myIdInCLoud, new GetCallback<ParseObject>() {
public void done(ParseObject upObj, ParseException e) {
if (e == null)
{
upObj.put("lat", "1");
upObj.put("lng", "2");
upObj.put("geoTime", "3");
upObj.saveInBackground();
Log.d("svcloud","inside func::");
}
else
{
Log.d("svcloud","error::" + e);
}
}
});
}
Note: all columns in the table are String type.
The function is getting called and also getting inside if condition, as its showing the log. But data isn't updating in parse.com.
Any solutions?
SOLVED!!
Just wrote the access permission to write for ACL and its working fine. :-)

Error while saving ParseRelation

I'm having some issues while trying to save a ParseRelation. I've tried creating the ParseUser first (I thought that was the problem) but it continued to happen.
Situation: I have 2 tables, one is User (Parse.com default) and a second one called Teams. Inside the latter, there's a ParseRelation to User. After saveInBackground is triggered I check the DataBrowser and I can see that the team was in fact created but the players added not in the relation.
My code:
ParseObject newTeam = new ParseObject(Constants.TABLE_TEAMS);
newTeam.put(Constants.ATTRIB_TEAM_NAME, nombreEquipo);
// FIXME ParseRelation not being saved
ParseRelation<ParseUser> playersRelation = newTeam
.getRelation(Constants.ATTRIB_TEAM_PLAYERS);
// Get Users from ListView
for (int i = 0; i < invitedPlayers.size(); i++) {
ParseUser pu = (ParseUser) viewPlayerList.getItemAtPosition(i);
playersRelation.add(pu);
Log.d(LOG_TAG,
"Player being added: "
+ pu.get(Constants.ATTRIB_USER_NAME));
}
newTeam.put(Constants.ATTRIB_TEAM_PLAYERS, playersRelation);
newTeam.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// setResult(RESULT_OK);
Toast.makeText(getApplicationContext(), "Team created.",
Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"ParseException: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Any ideas ? I've read the docs and also checked a few samples but can't seem to find out what's the problem.
Edit: Using Parse.com v1.5.0 and Android 4.4.2

aSmack - MultiUserChat.getJoinedRooms returns empty iterator

I'm working on an Android app that utilizes ASmack to send XMPP messages to and from a server in a background service. I can join a MultiUserChat (MUC) by calling MultiUserChat.join(connection.getUser());. I can confirm that I joined the chat by calling MultiUserChat.isJoined();, which returns true. Also, since I'm using www.hosted.im, I can see that I am in the conference room using their online UI. In another function, I try to retrieve the list of joined rooms, using MultiUserChat.getJoinedRooms(connection, connection.getUser());, but that returns an empty iterator.
private XMPPConnection connection;
/*... Connect to server and login with username and password ...*/
public Iterator<String> getJoinedRooms() {
Log.i(ChatListActivity.TAG, "Trying to get joined rooms");
Iterator<String> result = null;
if(connection != null) {
Log.i(ChatListActivity.TAG, "Returning joined chat rooms as " + connection.getUser());
result = MultiUserChat.getJoinedRooms(connection, connection.getUser());
while(result.hasNext()) {
Log.w(ChatListActivity.TAG, result.next());
}
} else {
Log.e(ChatListActivity.TAG, "Cannot get joined rooms. Connection == NULL");
}
if(result == null || (result != null && !result.hasNext())) {
ArrayList<String> resultArr = new ArrayList<String>();
resultArr.add(getString(R.string.no_chat_rooms_joined));
result = resultArr.iterator();
Log.i(ChatListActivity.TAG, "Returning EMPTY ITERATOR for joined chat rooms");
}
return result;
}
public void joinRoom(String room) {
if(connection != null) {
Log.i(ChatListActivity.TAG, "Joining room " + room);
// Create a MultiUserChat using a Connection for a room
MultiUserChat muc2 = new MultiUserChat(connection, "testroom#conference.konstadtest.p1.im");
try {
muc2.join(connection.getUser());
muc2.grantVoice(connection.getUser());
muc2.grantMembership(connection.getUser());
if(muc2.isJoined())
Log.w(ChatListActivity.TAG, "Joined room " + room + " as " + connection.getUser());
else
Log.w(ChatListActivity.TAG, "Failed to join " + room + " as " + connection.getUser());
} catch (XMPPException e) {
e.printStackTrace();
Log.w(ChatListActivity.TAG, "Cannot join room " + room);
}
} else {
Log.w(ChatListActivity.TAG, "Cannot join room " + room + " because connection is NULL");
}
}
What am I doing wrong? I called SmackAndroid.init(getApplicationContext()); before calling anything else.
Thank you for the help,
Chris
What i did is that i add a packet listener after getting get joined rooms.. i was also getting an empty list but when i debug i check that the rooms was getting returned in the resultant xml stanze that was sent by the server therefore i manually add ha packet listener like this:
public void AddPacketListener(){
PacketFilter filter = new IQTypeFilter(IQ.Type.RESULT);
MyService.getConnection().addPacketListener(new PacketListener()
{
public void processPacket(Packet paramPacket) {
if(paramPacket.getFrom().equals(MyService.getConnection().getUser())){
String xml=paramPacket.toXML();
String from[];
System.out.println(xml);
from=paramPacket.getFrom().split("/");
Pattern pattern = Pattern.compile("<item jid=\"(.*?)/>");
Matcher matcher = pattern.matcher(xml);
String parts[];
Roomlist.clear();
while (matcher.find()) {
parts=matcher.group(1).split("#");
Roomlist.add(parts[0]);
}
return;
}
}
},filter);
}

Categories

Resources