2

I tried to create a method that get a user by user's name. I'm using parse query. Here is my method:

 public ParseUser getUserByName(String name){
    ParseUser user;
    ParseQuery<ParseUser> query = ParseQuery.getQuery("_User");
    query.whereEqualTo("username", name);
    query.getFirstInBackground(new GetCallback<ParseUser>() {
        public void done(ParseUser result, ParseException e) {
            if (result== null) {
                Log.d("user", "Get user failed.");
            } else {
                user= result; // Compile error here, said: "Variable 'user' need to be declared final"
            }
        }
    });
    return user;
}

It complied error, and said that: "Variable 'user' need to be declared final". But, if I declared:

final ParseUser user;

so I can't assign the search result to user:

else {
          user= result; // Can't assign to user, because it's final.
     }

So How can I get and return the search result from query callback? Please help. Thanks.

1 Answer 1

2

try this

 public ParseUser getUserByName(String name){
    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereEqualTo("username", name);
    try {
        return query.getFirst();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

use

ParseUser parseUser = getUserByName("userName");
if(parseUser !=null){

}

Why getFirst();

Retrieves a list of ParseObjects that satisfy this query from the source in UI or Main Thread

why findInBackground();

Retrieves a list of ParseObjects that satisfy this query from the source in a background thread.

When we use findInBackground(); you can't return any result because your method will return result without waiting of done() response

Sign up to request clarification or add additional context in comments.

2 Comments

it worked! Big thank for your help.... and by the way. I see that you're using query.getFirst() instead of query.getFirstInBackground(). Could You please tell me what the differences between them. And how could i do if I want to use query.getFirstInBackground()? Thanks again
Thank You for your enthusiastic help...!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.