【问题标题】:Android - waiting for json to get value before continuing with methodAndroid - 在继续使用方法之前等待 json 获取值
【发布时间】:2017-05-19 10:07:18
【问题描述】:

我正在使用this 库来从服务器获取数据。数据在服务器中解码为JSONObject。我创建的方法将调用 url 并返回 mysql 表中的行数。

该方法正在运行,但是我无法从我的方法中正确返回值:

ParseLevels.java

static public int countLevels() {

        final int[] count = {0};
        AndroidNetworking.get("https://example.com/gameLevels.php?option=count")
                .setPriority(Priority.LOW)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // responce is {count:20}
                        try {
                            count[0] = response.getInt("count"); // this is getting the value of 20
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Log.d("responce_app", String.valueOf(count[0]));
                    }
                    @Override
                    public void onError(ANError error) {
                        // handle error
                        Log.d("responce_app", String.valueOf(error)); //Logs out 20
                    }
                });

        return count[0]; // return always 0
    }

当我从我的MainActivity 打来电话时 Log.d("responce_app", String.valueOf(ParseLevels.countLevels())); 该方法总是返回 0。

我知道返回是在获取 jsonObject 之前触发的,但是如何等待方法获取 jsonObject 并在返回值之后?

在 iOS 中我使用类似的东西:

static func getLevels(feedsArray: (levelsCount : [Int]) -> Void) {


}

如何将其转换为 Java?

【问题讨论】:

    标签: java android mysql json


    【解决方案1】:

    如何等待方法获取 jsonObject 并返回后 价值?

    两种选择:

    1.onResponse方法里面做代码,根据请求的结果来执行。

    2. 使用interface 创建事件监听器并在countLevels 方法调用者类中实现它以在onResponse 方法执行完成时执行代码块

    【讨论】:

    • 谢谢。我已经使用接口创建了事件监听器:public interface CountLevelCallback{ void afterCount(int count); }
    【解决方案2】:

    您应该查看库自述文件中的 Making Synchronous Request 示例: https://github.com/amitshekhariitbhu/Fast-Android-Networking

    ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                        .addPathParameter("pageNumber", "0")
                        .addQueryParameter("limit", "3")
                        .build();
    ANResponse<List<User>> response = request.executeForParsed(new TypeToken<List<User>>() {});
    if (response.isSuccess()) {
        List<User> users = responseTwo.getResult();
    } else {
        //handle error
    }
    

    您将在 response.isSuccess() 条件中返回您的计数。

    【讨论】:

    • 我已经尝试过了,但是我收到错误Cannot resolve method 'isSuccess()
    猜你喜欢
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2021-04-26
    相关资源
    最近更新 更多