简体   繁体   中英

Returning String from Parse.com query

So this doesn't seem to be working, but then again you can't return a String from a void method. The problem is I absolutely need to return a String based on how my classes are structured. What can I do to accomplish this? I need to get a value for the price of the item.

@Override
public String getCost() {
final String[] productValue = {"null"};
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Inventory");
        query.whereEqualTo("productName", "Capris");
        query.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> list, ParseException e) {
                if (e == null) { //no exception, hence success
                    for (ParseObject productCost : list) {
                        productValue[0] = (String) productCost.get("productPrice");
                        // Cannot return a value from a method with void result type
                        return productValue[0];
                    }
                }
                else {
                    // Cannot return a value from a method with void result type
                    return null;
                }
            }
        });
        return null;
    }

Your conditions are wrong

 @Override
    public String getCost() {
        final String[] productValue = {null};
        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>
        query.whereEqualTo("productName", Capris);
        query.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> list, ParseException e) {
                if (e == null) { //no exception, hence success
                    productValue[0] = list.get(0).getString("productPrice");
                }
            }
        });
        return productValue[0];
    }

In above code productValue[0] may be null as its an aysnc call So replace findInBackground with find()

public String getCost() {
    String productValue = null;
    ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Inventory");
    query.whereEqualTo("productName", "Capris");
    try {
        List<ParseObject> results = query.find();
        productValue = results.get(0).getString("productPrice");
        return productValue;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return productValue;
}

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