我的 Java 对象构造函数返回“null" [英] My Java object constructor returning “null”

查看:83
本文介绍了我的 Java 对象构造函数返回“null"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,该类具有用于各种活动的构造函数.但是,当我尝试订阅该对象以显示产品的一些图像、价格和名称时,我收到null"作为输出.但是当我尝试在 else 语句中传递相同的函数时,它工作但仍然返回 null.请帮助我理解为什么会出现此错误.并告诉我如何解决它提前谢谢.

I have created a class that has constructors for various Activity. However, when I try and subscribe to the object so as to display some images and price and names of a products, I receive "null" as the output. but when i try to pass the same function in the else statement it worked but still returned null. Please help me understand why am getting this error. and tell me how to solve it Thanks in advance.

mCompositeDisposable.add(mIMyRestaurantAPI.getFoodOfMenu(Common.API_KEY,
                event.getCategory().getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(foodModel -> {

                    if (foodModel.isSuccess()) {
                        adapter = new MyFoodAdapter(this, foodModel.getResult());
                        recycler_food_list.setAdapter(adapter);
                        recycler_food_list.setLayoutAnimation(mLayoutAnimationController);
                    } else {
                        Toast.makeText(this, "[GET FOOD RESULT]" + foodModel.getMessage(), Toast.LENGTH_LONG).show();
                    }

                    mDialog.dismiss();

                }, throwable -> {
                    mDialog.dismiss();
                    Toast.makeText(this, "[GET FOOD]" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                }));    

我不断得到 GET FOOD RESULT=null ..这是我的 FOODMODEL 构造函数的样子

i keep getting GET FOOD RESULT=null..here is what my FOODMODEL construtor looks like

public class FoodModel {
private boolean success;
private String message;
private List<Food> result;

public boolean isSuccess() {
    return success;
}

public void setSuccess(boolean success) {
    this.success = success;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public List<Food> getResult() {
    return result;
}

public void setResult(List<Food> result) {
    this.result = result;
}    

这是 FOOD 构造函数的样子

and here is what the FOOD constructor looks like

public class Food {

private int id;
private String name;
private String description;
private String image;
private Double price;
private boolean isSize;
private boolean isAddon;
private int discount;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public Double getPrice() {
    return price;
}

public void setPrice(Double price) {
    this.price = price;
}

public boolean isSize() {
    return isSize;
}

public void setSize(boolean size) {
    isSize = size;
}

public boolean isAddon() {
    return isAddon;
}

public void setAddon(boolean addon) {
    isAddon = addon;
}

public int getDiscount() {
    return discount;
}

public void setDiscount(int discount) {
    this.discount = discount;
}    

这是我使用改造从后端传递连接的地方.

and this is where i pass the connection from the backend using retrofit.

 @GET("food")

Observable<FoodModel> getFoodOfMenu(@Query("key") String apiKey,
                                    @Query("menuId") int menuId);    

这是我使用 nodejs 的 api 后端..

here is the api backend i used nodejs..

router.get('/food', function (req, res, next) {
if (req.query.key == API_KEY) {
    req.getConnection(function (error, conn) {
        var menu_id = req.query.menuId
        if (menu_id != null) {
            conn.query('SELECT id,name,description,image,price, CASE WHEN isSize=1 THEN \'TRUE\' ELSE \'FALSE\' END as isSize,'
                +'CASE WHEN isAddon=1 THEN \'TRUE\' ELSE \'FALSE\' END as isAddon,'
                + 'discount FROM Food WHERE Id in (SELECT foodId FROM Menu_Food WHERE MenuId=?)', [menu_id], function (err, rows, fields) {

                if (err) {
                    res.status(500)
                    res.send(JSON.stringify({ sucess: false, message: err.message }))
                }
                else {
                    if (rows.length > 0) {
                        res.send(JSON.stringify({ sucess: true, result: rows }))
                    }
                    else {
                        res.send(JSON.stringify({ sucess: false, message: "Empty" }))
                    }
                }
            })
        } else {
            res.send(JSON.stringify({ sucess: false, message: "Missing menu_id" }))
        }
    })
}
else {
    res.send(JSON.stringify({ success: false, message: "Wrong api key marfe" }))
}

})

这里是json响应

{"sucess":true,"result":[{"id":1,"name":"ROASTED QUARTER CHICKEN","description":"Served with mushroom gravy, cranberry & mint sauces","image":"http://10.0.2.2:3000/4_roasted_quarter_chicken_with_special_sauces.jpg","price":25,"isSize":"FALSE","isAddon":"FALSE","discount":0},{"id":2,"name":"CURRY CHICKEN","description":"Chicken served in curry that is made from more than 10 spices to bring out the authentic traditional taste. Served with rice and 3 side dishes\r\n","image":"http://10.0.2.2:3000/2_curry_chic.jpg","price":25,"isSize":"FALSE","isAddon":"FALSE","discount":0},{"id":3,"name":"\r\nRENDANG CHICKEN","description":"Simmered chicken in spices. Served with rice and 3 side dishes","image":"http://10.0.2.2:3000/1_classic_rendang.jpg","price":25,"isSize":"FALSE","isAddon":"FALSE","discount":0},{"id":4,"name":"HERBAL STEAMED CHICKEN","description":"Steamed chicken with red dates and mushroom. Served with rice and 3 side dishes","image":"http://10.0.2.2:3000/3_herbal_steamed_chic.jpg","price":25,"isSize":"FALSE","isAddon":"FALSE","discount":0}]}    

推荐答案

您必须从 api 响应中获取 null.或者您的 Java 对象及其字段应该与您的 json 响应中的属性匹配.

You must be getting null from the api response. Or your Java Object and its fields should match the attributes in your json response.

例如你有这个 json{国家":[{"name": "以色列","电话代码": "972",代码":IL"},{"name": "阿富汗","电话代码": "93",代码":AF"},{"name": "阿尔巴尼亚","电话代码": "355",代码":AL"}]}

For example you have this json{ "countries": [ { "name": "Israel", "phoneCode": "972", "code": "IL" }, { "name": "Afghanistan", "phoneCode": "93", "code": "AF" }, { "name": "Albania", "phoneCode": "355", "code": "AL" }]}

那么你的模型应该是这样的

Then your model would be like this

public class CountryModel {

private List<Country> countries = new ArrayList<>();

public List<Country> getCountries() {
    return countries;
}

public void setCountries(List<Country> countries) {
    this.countries = countries;
}

public static class Country {
    private String name;
    private String code;
    private String phoneCode;

    public Country(String name, String code, String phoneCode) {
        this.name = name;
        this.code = code;
        this.phoneCode = phoneCode;
    }


    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhoneCode() {
        return phoneCode;
    }

    public void setPhoneCode(String phoneCode) {
        this.phoneCode = phoneCode;
    }

}

}

使用您的 json,您的 Java 模型应该如下所示

with your json your Java model should look like this

public class Example {

private Boolean sucess;
private List<Result> result = null;

public Boolean getSucess() {
return sucess;
}

public void setSucess(Boolean sucess) {
this.sucess = sucess;
}

public List<Result> getResult() {
return result;
}

public void setResult(List<Result> result) {
this.result = result;
}

}

这篇关于我的 Java 对象构造函数返回“null"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆