简体   繁体   中英

Returning a String from ParseQuery method is null

I want to return a String to this statement: String replyUsername = queryUsernameById(objectId);

Here is the query method:

public String queryUsernameById(String objectid) {

        final String[] username = {null};
        ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
        userQuery.whereContains(ParseConstants.KEY_OBJECT_ID, objectid);
        userQuery.getFirstInBackground((user, e) -> {

            // We found messages!
            if (e == null) {

                username[0] = user.getUsername();

            } else {
                e.printStackTrace();
            }
        });
        return username[0];
    }

When I display the String it returns as null. How can I fix this?

You haven't shown the rest of your code, where you actually use this value, so it's hard to say for sure, but my guess is that the asynchronasity is messing you up here. The query runs in the background, so if you use this value too close to the function call, the query hasn't actually returned yet. You should assign the value to the label within the completion handler, or use a key value listener that waits for the update to update the label.

Additionally, there is a query method specifically for getting an object by Id, rather than adding objectId as a query constraint. query.get(objectId) or something similar, though I'm less familiar with the Java SDK. It has the benefit of returning a 101 error for the object not existing, rather than an empty array / object with a success callback.

I changed the method to this:

public String queryUsernameById(String objectId) {

        String username;
        ParseQuery<ParseUser> query = ParseUser.getQuery();
        query.whereContains(ParseConstants.KEY_OBJECT_ID, objectId);
        try {
            ParseUser result = query.getFirst();
            username = result.getUsername();
            return username;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

It works but it's not totally reliable. Sometimes it returns null. Strange.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM