将 REST API 响应到 Fragment - Android Studio

Response of a REST API into Fragment - Android Studio

我是 android 开发 APP 的新手。我想开发一个分为片段的应用程序,每个片段都填充了调用 REST APIs.

获得的数据

我遵循了不同的教程,但我遇到了这个问题:该片段没有显示任何内容。

我从 android 工作室的“Tabbed Activity”开始我的项目:

这是我的片段(我称之为 api):

public class Calendar extends Fragment {

private static final String baseUrl = "https://xxx";
private static final String events = "/wp-json/sportspress/v2/events";
EventsJsonObjectToMatchesConverter converter;

ArrayList<Matches> matches = new ArrayList<>();

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.calendar_layout,container, false);
    return rootView;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    this.getEvents();

    ListView lv = (ListView)view.findViewById(R.id.matches);

    MatchesAdapter adapter = new MatchesAdapter(this.getContext(),
            R.layout.matches_layout,
            matches);

    lv.setAdapter(adapter);
}

private void getEvents() {

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
    String url =getString(R.string.baseUrl) + getString(R.string.eventsEndpoit);

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    Matches match = new Matches();
                    match.setHomeTeam("simone");
                    match.setAwayTeam("gaspa");
                    match.setResultHome(2);
                    match.setResultAway(1);
                    match.setDate("05/10/2021 - 10:00");
                    matches.add(match);

                    System.out.println(matches.size());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        //This is for Headers If You Needed
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json; charset=UTF-8");
            params.put(
                    "Authorization",
                    String.format("Basic %s", Base64.encodeToString(
                            String.format("%s:%s", getString(R.string.user), getString(R.string.password)).getBytes(), Base64.DEFAULT)));
            return params;
        }


    };

    // Add the request to the RequestQueue.
    queue.add(stringRequest);


}


}

这是我的适配器:

public class MatchesAdapter extends ArrayAdapter<Matches> {

private ArrayList<Matches> matchList;

public MatchesAdapter(Context context, int matches_layout, ArrayList<Matches> matches) {
    super(context, matches_layout);
    this.matchList = matches;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    int phraseIndex  = position;

    if(convertView == null){
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.matches_layout,parent, false);
    }

    TextView home = convertView.findViewById(R.id.squadra_casa);
    TextView away = convertView.findViewById(R.id.squadra_trasferta);
    TextView home_result = convertView.findViewById(R.id.risultato_casa);
    TextView away_result = convertView.findViewById(R.id.risultato_trasferta);
    TextView group = convertView.findViewById(R.id.girone);
    TextView date = convertView.findViewById(R.id.data_ora);

    home.setText(matchList.get(position).getHomeTeam());
    away.setText(matchList.get(position).getAwayTeam());
    home_result.setText(matchList.get(position).getResultHome());
    away_result.setText(matchList.get(position).getResultAway());
    group.setText(matchList.get(position).getGroup());
    date.setText(matchList.get(position).getDate());

    return convertView;
}
}

我 运行 应用程序,但我没有看到任何东西:

注意:我在 onResponse() 方法中模拟了对象 Match 来测试代码。我已经看到 Rest API 被正确调用并且 return 所需的数据

感谢您的帮助!

简单看一下代码,感觉写得不错。您缺少的要点是 API 调用是异步的,并且在 API returns 任何结果之前填充适配器。尝试在 StringRequest 调用的 OnResponse 回调中填充适配器,像这样(对不起,我没有尝试 运行 它,但我认为给你一个提示可能会有所帮助):

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                matches = ParseTextResultToMatchesObjects(response);
                adapter = new MatchesAdapter(this.getContext(),
                    R.layout.matches_layout,
                    matches);
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
    ...

编辑: 对于将来关心这个的任何人:整个操作都放在 onViewCreated 而不是 onCreateView 中,这导致了更多的复杂性(我不确定为什么),但是我写的关于操作的异步性和填充适配器的内容是错误的时间停止...