在HTTP请求返回值之前,禁止前进功能

时间:2019-04-29 11:40:50

标签: java android http

我有一个带有某些操作和参数的HTTP请求发送到服务器。它返回一个响应。我希望该函数等待,直到它获得响应并根据我的选择映射数据(例如,将值设置为Event的对象类)。然后它将把这些数据从调用它的地方返回给函数。

例如: 我从这里调用getEventWithID:

public uk.co.createanet.bloc.Networking.DynamoDB.Mapping.Event fetchAdvertEvent(Long eventID) {
        return EventHelper.getEventWithID(eventID);
    }

getEventWithID-这将调用HTTP请求并获取响应。我希望该函数在收到服务器的响应之前不返回。

public static Event getEventWithID(Long eventID, IHelperRequestCompletion<Event> completion) {

        Event event = new Event();

        Map<String, Object> params = new HashMap<>();
        params.put("eventID", eventID);

        HttpHelper.getInstance().makeApiHttpRequestNewServer("get-event", params, new IHelperRequestCompletion<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    event.setID(response.getLong("uniqueID"));
                    event.setPlaceID(response.getLong("placeID"));
                    event.setType(response.getString("type"));
                    event.setTimestamp(response.getDouble("date"));
                    if(response.toString().contains("people")){
                        JSONArray attendingPPL = response.getJSONArray("people");
                        Set<Long> attendingPPLList = new HashSet<>();

                        for (int i = 0; i < attendingPPL.length(); i++) {
                            attendingPPLList.add(Long.parseLong(attendingPPL.getString(i)));
                        }
                        event.setAttendingPeopleIDs(attendingPPLList);
                    }

                    if(event.getID()!=null) {
                        AppDatabase.getAppDatabase(BlocApplication.getAppContext()).eventDao().insertAll(event);
                        if(completion !=null){
                            completion.onResponse(event);
                        }
                    }

                }catch (Exception err){
                    Log.v("Error in getEventByID", err.getLocalizedMessage());
                }

            }

            @Override
            public void onError(Throwable error) {
                Log.v("Error in getEventByID", error.getLocalizedMessage());
            }

        });

return event;
    }

1 个答案:

答案 0 :(得分:0)

如果要进行异步调用并返回一个值,则此功能将无法正常工作,要实现这种功能,您必须创建一个接口并通过侦听器返回值。