Reputation: 121
I am making a social app for Android and I'm using Parse to deal with the server-side stuff.
I am making a list of posts and I have to get the username of the post's author. I have a pointer the the _User class in my Post class and I get the author of a given post. However, when I try to get that user's username, something goes wrong.
This is the current code:
parseQueryAdapter = new ParseQueryAdapter<HoodPost>(getActivity(), HoodPost.class) {
@Override
public View getItemView(HoodPost post, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.hood_post_item, null);
}
TextView postTextView = (TextView) view.findViewById(R.id.text_view);
TextView authorView = (TextView) view.findViewById(R.id.author_view);
ParseUser author = post.getAuthor();
postTextView.setText(post.getText());
authorView.setText(author.getUsername());
return view;
}
}
I have also tried:
author.getString("name");
(this is also a field in my _User table)
and
author.getString("username");
The error it throws is:
java.lang.IllegalStateException: ParseObject has no data for this key. Call fetchIfNeeded() to get the data.
None of the two fields in empty in any of my table rows. I have searched for a person with a similar problem, but to no avail.
Any suggestions?
Upvotes: 2
Views: 3906
Reputation: 53
You can use include
:
ParseQuery<Survey> query = ParseQuery.getQuery("Post");
query.include("Post.User.Author");
Upvotes: 0
Reputation: 187
@Yasen Petrov is correct that you need to use fetchIfNeeded() as the exception says. The reasoning behind this is that with relationships like this in Parse (in your case your Author and Post), the related objects aren't automatically fetched. Thus, if you fetch your author first as Yasen details, it will work.
Alternative change to your Author.java code:
try {
name = fetchIfNeeded().getString("name");
} catch (ParseException e) {
Log.e(TAG, "Something has gone terribly wrong with Parse", e);
}
Upvotes: 1
Reputation: 121
I actually found an answer in this question here
The thing that is not mentioned there is that you have to surround it with a try-catch, like so:
String name = "";
try {
name = author.fetchIfNeeded().getString("name");
} catch (ParseException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
Upvotes: 9