gpt4 book ai didi

java - 使用Volley在Util类中调用Web服务后如何返回值?

转载 作者:行者123 更新时间:2023-12-02 01:36:39 27 4
gpt4 key购买 nike

我想在从 Volley 中的 Web 服务获取响应并在 Activity 中调用值后返回字符串值。下面是我的代码;

Utils.java

    public static String getitemCountPrice(String cartId) {

try {
if (Utils.isNetworkAvailable(mContext)) {
HashMap<String, String> params = new HashMap<>();
params.put(CONSTANTS.API_param_cartid, cartId);
params.put(CONSTANTS.API_param_token, Utils.getToken());
JSONObject postdata = new JSONObject(params);

try {
YupITApplication.getJsonWithHTTPPostResponse(params, mContext, 1, (id, jsonResult) -> {
if (jsonResult.getString(mContext.getString(R.string.status)).equalsIgnoreCase(mContext.getString(R.string.success))) {
itemCountPrice = jsonResult.getJSONObject("Data").getString("Count") + ","
+ jsonResult.getJSONObject("Data").getString("TotalPrice");
Log.e("itemCountPrice.............", "" + itemCountPrice);
// Here I get value
} else {
itemCountPrice = "0,0";
}
}, Utils.cartitemcount, postdata);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, mContext.getString(R.string.no_server_found), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}

return itemCountPrice;
// Here I get null and this is called before web service call
}

MainActivity.java

Utils.getitemCountPrice(cart_id));

每次我从上述方法中得到 null

最佳答案

您的 return 语句将在进行 API 调用后立即执行,并且不会等待响应,因为它是以同步方式编写的。您可以借助界面通知结果

interface APIListener{
public void onResponse(String itemPrice);
}

你的方法看起来像这样

    public static void getitemCountPrice(String cartId, APIListener apiListener) {

try {
if (Utils.isNetworkAvailable(mContext)) {
HashMap<String, String> params = new HashMap<>();
params.put(CONSTANTS.API_param_cartid, cartId);
params.put(CONSTANTS.API_param_token, Utils.getToken());
JSONObject postdata = new JSONObject(params);

try {
YupITApplication.getJsonWithHTTPPostResponse(params, mContext, 1, (id, jsonResult) -> {
if (jsonResult.getString(mContext.getString(R.string.status)).equalsIgnoreCase(mContext.getString(R.string.success))) {
itemCountPrice = jsonResult.getJSONObject("Data").getString("Count") + ","
+ jsonResult.getJSONObject("Data").getString("TotalPrice");
Log.e("itemCountPrice.............", "" + itemCountPrice);
apiListener.onResponse(itemCountPrice);
// Here I get value
} else {
itemCountPrice = "0,0";
apiListener.onResponse(itemCountPrice);
}
}, Utils.cartitemcount, postdata);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, mContext.getString(R.string.no_server_found), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

关于java - 使用Volley在Util类中调用Web服务后如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55156568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com