how to cast a ParseObject to ParseUser - android

Hi I was wondering how I can get a ParseUser object from a ParseObject. I need to do this because a ParseQuery returns a List. Here is my code and thank you for the help!
// get the currentUser
currentUser = ParseUser.getCurrentUser();
List<ParseObject> friendsList = currentUser.getList("friendsList");
// search for the person the user wants to add as a friend
List<ParseObject> userResults = new ArrayList<ParseObject>();
ParseQuery otherUserQuery = ParseUser.getQuery();
otherUserQuery.whereEqualTo("username", "jyo2");
try {
userResults = otherUserQuery.find();
} catch (ParseException e1) {
// fail
e1.printStackTrace();
}
// get the friend from the query if there was one and add it to the
// currentUser friends list
if (userResults.size() != 0) {
ParseObject currentObject = userResults.get(0);
friendsList.add(currentObject);
currentUser.put("friendsList", friendsList);
}
// save the update
try {
currentUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try to view the friends
List<ParseObject> currentFL = currentUser.getList("friendsList");
ParseObject currentPU = currentFL.get(0);
System.out.println("THIS IS SIZE" + currentFL.size());
System.out.println(currentPU.get("name"));

Use the existing "User" class in Parse but subclass it using
#ParseClassName("_User")
public class PUser extends ParseUser {
As per this article. You actually specifically need to refer to the _User "ParseClassName" when subclassing this object. It's super hairy, I was stuck on this for ages because for other classes you only need to "register" the class with Parse using it's literal name as per the Parse Data Browser, which in this case is "User", "Info", "Post" etc, but the User class specifically requires the underscore
Edit Sorry, I should have mentioned, then you simply cast the subclass PUser when you get your returned objects from the query. You may need to change the query to be a User query instead of an object one too.
I know this is an old question, but this wasn't clear for me and there wasn't a complete thread on the issue I had, on SO. Hope this helped.

I don't think you need to "cast" is to ParseUser, a parseuser is a parseobject as well, apart from having some basic pre-defined properties attached to it, which you can anyways query like you'd query any other parseobject

Related

Parse Relation Query:How to Get Only one user from relation list

Hi there I'm new to parse, android and stackoverflow.com, here is my question
I've two classes on parse one is "post" and other is "user" class. Anyone can like post and dislike post.
I've created two relation column "whoLiked" and "whoDisliked" which points the list of users who has liked/disliked a specific post.
When I'm showing the post to the user I want the current User to like/dislike the post Only once which I've set properly.
But only thing I'm not getting is how can I fetch only currentuser from thisPost object.
I don't wanna fetch the list of user who liked this post I just want to know if current User has liked it or not.?
I'm new to stackoverflow.com plz ignore if any mistakes here. Thanks u all in advance.
Below is the query to fetch all the liker
ParseObject post = ...
// create a relation based on the authors key
ParseRelation relation = book.getRelation("whoLiked");
// generate a query based on that relation
ParseQuery query = relation.getQuery();
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> comments, ParseException e) {
if (e == null) {
// "user" is now a list of the user who liked
} else {
// Something went wrong...
}
}
});
Just add a constraint to check if the objectId is the same as the currentUsers's objectId:
// create a relation based on the authors key
ParseRelation relation = book.getRelation("whoLiked");
// generate a query based on that relation
ParseQuery query = relation.getQuery();
// ADD CONSTRAINT HERE:
ParseUser currentUser = ParseUser.getCurrentUser();
query.whereEqualTo("objectId", currentUser.getObjectId());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> comments, ParseException e) {
if (e == null) {
// "user" is now a list of the user who liked
} else {
// Something went wrong...
}
}
});

Android Parse.com query user by pointer

I have a problem querying the data of a user using pointer, so this is my tables (class):
_User
objectId<string> | username<string> | ...
Posts
objectId<string> | post<string> | writerId <pointer>(_User)
The writerId contains the user id of the writer of the post.
I'm showing the posts in a custom ListView in this way:
variables_posts = new ArrayList<VariablesPosts>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Posts");
query.selectKeys(Arrays.asList("post"));
query.include("writerId");
on = query.find();
for (ParseObject post : on) {
VariablesPosts map = new VariablesPosts();
map.setWriter((String) post.get("username"));
map.setPost((String) post.get("post"));
variables_posts.add(map);}
The problem is that the writerId is a pointer and not a string if I put
map.setWriter((String) post.get("writerId"));
The app will crash, so I used from another help the line query.include("writerId"); to directly get the username but this line:
map.setwriter((String) post.get("username"));
is crashing the app too, when I delete it the app works fine, so in my case how can I get the username from User class by the pointer writerId?
I don't know exact Java syntax, but when you include writerId and then want to get username of that writerId User, you must first get the User object from Post's writerId .. something like:
(String)((ParseUser)post.get("writerId")).get("username")
Your naming of the pointer column is a little misleading as the column does not contain IDs. You should call it writer instead.
To get the username, do this:
query.include("writerId");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject post : postList) {
ParseObject writer = post.getParseObject("writerId");
String userName = writer.getString("username");
// .. (do whatever with userName)
}
} else {
Log.d("post", "Error: " + e.getMessage());
}
}
});

Retrive value of a column in parse.com

I have made a table in Parse.com using Dashboard name Blogs. I have made a column url type String using Dashboard inside it where I have to post blogs url and I have posted some url inside this column by adding rows. Now I am trying to get these values inside my application by using this code in onCreate() method.
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("Blogs");
parseQuery.whereEqualTo("url", true);
List<ParseObject> objects = null;
try {
objects = parseQuery.find();
}
catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
I am getting objects of size 0. I am unable to understand how to get my url column all values.
Read the api docs carefully.
I believe you want to query if the urls exists in the column. (since you have used parseQuery.whereEqualTo("url", true);)
From the docs,
public ParseQuery<T> whereEqualTo(String key,
Object value)
What it does : Add a constraint to the query that requires a particular key's value to be equal to the provided value.
So in this case for url, the value should be a String (which you want to match to) if you have defined the column as String. Putting value as boolean will give you undesired result.
If you want to check if the column url exists for the object,
then use whereExists(String key).
Use like this
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("Blogs");
parseQuery.whereEqualTo("url","true");
List<ParseObject> objects = null;
try
{
objects = parseQuery.find();
}
catch (ParseException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}

How to get objectId on Parse.com android

It is said that we can retrieve our data if we are having objectId for that particular row, but it is auto generated and we cant insert it while setting data , so how to get data if i am not having object id , or any other means so that i can set objectId on my means.
Code is here as in comment:
ParseObject gameScore = new ParseObject("My Parse File");
String objectId = gameScore.getObjectId();
ObjectId doesnt't exist until a save operation is completed.
ParseObject gameScore = new ParseObject("My Parse File");
To retrieve the object id you need to save the object and register for the save callback.
gameScore.saveInBackground(new SaveCallback <ParseObject>() {
public void done(ParseException e) {
if (e == null) {
// Success!
String objectId = gameScore.getObjectId();
} else {
// Failure!
}
}
});
ObjectId can be retrieved from the original ParseObject(gameScore) once the done save callback is fired.
You can use this for getting current user object id
ParseUser pUser= ParseUser.getCurrentUser();
String objId= pUser.getObjectId();
not sure if this will apply to android , but I was trying to retreive the objectid, but for an entry that is already created. I did something like this and it worked.
ParseObject gameScore = new ParseObject("My Parse File");
var obId = gameScore.id;
Got it from the Javascript docs on Parse.com
The three special values are provided as properties:
var objectId = gameScore.id;
var updatedAt = gameScore.updatedAt;
var createdAt = gameScore.createdAt;
You can't unfortunately use the ObjectId until the object's been saved. I'm having this same problem now. The only solution I can think of, and posted a similar question relating to it here
My solution would be to make a tempId on the object and refer to that locally until it has an actual ObjectId, perhaps using a saveInBackground or saveEventually() callback to set other objects relating to it, to it's newly created ObjectId instead of it's old temp one.. when it's made available
It takes times for your values to be stored in table. Use this to get ObjectId
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
// Saved successfully.
Log.d("main", "User update saved!");
Log.d("main", "ObjectId "+gameScore.getObjectId());
} else {
// The save failed.
Log.d("main", "User update error: " + e);
}
}
});
In case you're handling the thread yourself:
First save:
gameScore.save();
Then you'll be able to access the id:
String parseId = gameScore.getObjectId();

Parse fetchIfNeeded() not working

I have 2 pointer objects(pointing to ParseUser) in my table "Attack".It seems these pointer objects take a while to get retrieved.Hence my code directly didnt work and gave me the exception:
java.lang.IllegalStateException: ParseObject has no data for this key. Call fetchIfNeeded() to get the data.
I then did the needful surrounding the fetchIfNeeded function with a try-catch block:
ParseObject battle = null;
try {
battle = objects.get(0).fetchIfNeeded();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ParseUser attacker1 = battle.getParseUser("Attacker");
Log.i("dontest",attacker1.getUsername());
It is still returning the same.I even checked with isDataAvailable function and it returned true.Any way around this?
P.S.: My query returns exactly 1 row which I checked with the size() function.
Here's the documentation describing fetchIfNeeded() function.
Use Your query like this..
ParseQuery<ParseObject> pQueryFromAttack = new ParseQuery<ParseObject>("Attack");
// use include to fetch details while quering----increase loading speed by doing this.
pQueryFromAttack.include("pointer to _user table");
List<ParseObject> listObj = pQueryFromAttack.find();
for eg:
String userName =listObj.get(0).fetchIfNeeded().getString("name");
Use it like this...

Categories

Resources