【问题标题】:Java Object in Android Studio Which is Constructed by Call to Rest APIAndroid Studio中通过调用Rest API构造的Java对象
【发布时间】:2020-12-12 02:24:49
【问题描述】:

我正在 Android Studio 中编写一个应用程序,通知用户火车时间。我有一个名为 Journey 的类,我的想法(不确定这是否是正确的方法,因为我是 Java 和 Android 开发的新手)是根据 API 返回的响应设置属性。对 API 的调用正在工作,我可以设置属性,但我怎样才能让调用类在完成对 API 的调用并完全加载属性之前进行监听。

我目前的代码如下:

public Journey(String startCode, String endCode, Activity activity) {
    //Connect to the API and set up the journey object

updateJourney(startCode,endCode,activity);


}


public void updateJourney(String startCode, final String endCode, Activity activity) {
    queue = Volley.newRequestQueue(activity);
    final Journey journeyClass = this;

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,URL_LEFT + URL_START + startCode + URL_DEST + endCode,null,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d("Response", response.toString());

                if (response.length() != 0) {
                    try {
                        JSONObject returnedJourney = response.getJSONObject(0);
                        journeyClass.setStartCode(returnedJourney.getString("station"));
                        journeyClass.setEndCode(endCode);

                        JSONArray services = returnedJourney.getJSONArray("services");
                        JSONObject firstService = services.getJSONObject(0);
                        journeyClass.setDepartTime(firstService.getString("depfriendly"));
                        journeyClass.setArriveTime(firstService.getString("arrfriendly"));
                        journeyClass.setStatus(firstService.getString("schedule_status"));

                        Log.d("journey arrival",journeyClass.getArriveTime());

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    //Returned response is empty - deal wth
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO: Handle error
                //Log.d("URL", URL_LEFT + URL_START + startCode + URL_DEST + endCode);
                VolleyLog.d("error", error.getMessage());
                error.printStackTrace();
            }
        });

queue.add(jsonArrayRequest);

}

这整个事情可能有一套固定的方法,但就像我说的那样,我对此很陌生。我在网上搜索过,但不太确定你是如何在 Java 中做到这一点的。我不确定设置类的实例是否正确,但我认为这是从内部类中设置属性的一种方式。

更新:

我在侦听器中使用以下内容,这似乎可以正常工作。我需要整理所有代码,如果这可以作为解决方案,我稍后会回来。在接下来的 8 个小时里,我现在必须去上班。

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        TextView station = getActivity().findViewById(stationFieldId);
        station.setText(stationName);
        TextView timeField = getActivity().findViewById(timeFieldId);
        timeField.setText(journey.getDepartTime());
    }
});

【问题讨论】:

  • 我不确定如果我理解正确,您是否希望在响应成功或失败后通知调用者类?请澄清
  • 据我了解,对 API 的调用是异步发生的,因此在调用构造函数的片段类中,如果您运行 Log.d("journeyarrival",journey.getArriveTime());调用构造函数后。我对那里发生的事情的假设是,它还没有完成 API 调用,因为对象正在构建响应侦听器类。
  • 我尝试将 API 调用移至调用类,但遇到了同样的问题。如果我尝试从侦听器中更新 TextView,那么我会得到一个空对象异常。我在网上找不到任何可以清楚地解释如何做到这一点的东西。有人可以帮忙吗?
  • 您编写网络逻辑以在其他类中请求某些内容,并使用侦听器将数据传递回目标,绘制您需要的图表。
  • 我不确定如何绘制它的图表,但基本上我需要执行对 API 的调用,然后使用从 API 检索到的数据更新 UI 中的 TextView。

标签: java android asynchronous android-volley


【解决方案1】:

这是我最后使用的对我有用的代码。我已经编辑了它对 UI 元素所做的很多事情,以包括它设置 TextViews 的部分

private void getJourneyAndDisplay(String startCode, final String destCode, final String stationName, final int stationFieldId, final int timeFieldId, final int statusFieldId, final boolean out) {
    queue = Volley.newRequestQueue(getActivity());
    journey = new Journey();

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Journey.URL_LEFT + Journey.URL_START + startCode + Journey.URL_DEST + destCode, null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    if (response.length() != 0) {
                        try {
                            //Make panel visible as it has returned results
                            panel.setVisibility(View.VISIBLE);

                            JSONArray services = returnedJourney.getJSONArray("services");
                            if (services.length() > 0) {
                     //Journey object is configured

                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Activity act = getActivity();
                                        TextView station = act.findViewById(stationFieldId);
                                        station.setText(stationName);
                                        TextView timeField = act.findViewById(timeFieldId);
                                        timeField.setText(journey.getDepartTime());
                                        TextView statusField = act.findViewById(statusFieldId);
                                        statusField.setText(journey.getStatus());
                                    }
                                });

                            } else {
                 //Deal iwth no joruney
                            }
                        } catch (JSONException e) {
                            //Display message to inform user that the data cannot be retrieved
                        }
                    } else {
                        //Returned response is empty
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
        //Handle reponse
                }
            });
    queue.add(jsonArrayRequest);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多