【问题标题】:Trying to return an Arraylist from Volley Callback尝试从 Volley Callback 返回一个 Arraylist
【发布时间】:2021-07-24 17:41:04
【问题描述】:

我对编程很陌生,所以如果有些东西完全是错误的,我深表歉意,这是我的第一个应用程序。

我有一个片段,我试图从负责从 JSON 存储库中提取信息的不同类中获取 ArrayList。

这个想法是从负责提取数据的类中提取数据,将其传递给片段,然后在片段内部使用它收到的 ArrayList 填充一个列表。

这是 PullData 类中负责拉取信息的代码:

public class PullData {
   
 ArrayList<InformationField> informationList;
 RequestQueue queue;
 Context context;

    public PullData(Context context){
        this.context = context;
        queue = Volley.newRequestQueue(context);
       informationList  = new ArrayList<>();
     
    }

    public ArrayList<InformationField> getInfo(){
        parseMain(new VolleyCallBack() {
            @Override
            public void onSuccess(ArrayList<InformationField> info) throws JSONException {
                informationList = info;
            }

            @Override
            public void onError(String result) throws Exception {

            }


        });
     return informationList;
    }


    public void parseMain(final VolleyCallBack callBack){



        String url = "https://data.gov.il/api/action/datastore_search?resource_id=053cea08-09bc-40ec-8f7a-156f0677aff3&filters={%22mispar_rechev%22:%22" + plateNumber + "%22}&include_total=1";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {


                    JSONObject result = response.getJSONObject("result");
                    JSONArray jsonArray = result.getJSONArray("records");
                    String test = result.getString("total");

             
                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject number = jsonArray.getJSONObject(i);

                            model = number.getString("degem_nm");
                            String modelcd = number.getString("degem_cd");



                            carMaker = number.getString("tozeret_nm");
                            subtype = number.getString("kinuy_mishari");
                            carYear = number.getString("shnat_yitzur");
                            carGimur = number.getString("ramat_gimur");
                            ownership = number.getString("baalut");
                            date = number.getString("tokef_dt");
                           

                          


                            informationList.add(new InformationField("maker", carMaker, "maker", carModel));
                            informationList.add(new InformationField("year", carYear, "subtype", subtype));
                            informationList.add(new InformationField("ownership", ownership, "date", date));

                            callBack.onSuccess(informationList);


                        



                } catch (JSONException e) {


                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {




            }
        });

        queue.add(request);

    }

这是我的回调接口

package com.OMApp.rechev;


import org.json.JSONException;

import java.util.ArrayList;

public interface VolleyCallBack {
    void onSuccess(ArrayList<InformationField> info) throws JSONException;
    void onError(String result) throws Exception;
}

这是我尝试使用 getInfo 从 PullData 传递 ArrayList 的片段


public class MainRepo extends Fragment {


    ListView list;
    ArrayList<InformationField> informationList;


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


        PullData data = new PullData(getContext());
        informationList = data.getInfo();

        list = view.findViewById(R.id.tv);
        customAdapter arrayAdapter = new customAdapter(getContext(), R.layout.row, informationList);
        list.setAdapter(arrayAdapter);


    }

}

问题是,当我在 MainRepo.java 中创建一个 PullData 对象并使用 getInfo() 方法时,我得到一个空的 ArrayList,似乎 getInfo 跳过了 onSuccess 方法并直接进入 return 语句,因此返回一个空数组列表。

【问题讨论】:

  • 您忘记提及您的问题或提出问题?
  • @HenryTwist 抱歉,如果不清楚,我已经编辑并添加了更多信息。
  • 请尝试使用您的断点和/或打印语句进行调试。检查informationList 的设置是否符合您的预期。您可以在 IntelliJ 中设置字段观察器,例如:jetbrains.com/help/idea/using-breakpoints.html#field_watchpoint
  • 使用调试器我注意到getInfo 方法运行了两次,第一次它直接返回informationList; 语句,第二次它只是运行其中的onSuccess 方法,不返回任何东西。好像订单关闭了,我需要它先调用onSuccess,然后才在getInfo方法中返回。
  • 您错误地认为onSuccess 会在您调用parseMain 时立即运行。 getInfo 不返回来自onSuccess 的结果,它发送一个网络请求并注册一个回调以在完成时运行。所以getInfo 不会运行两次,它会运行一次来​​注册回调。然后onSuccess 在请求完成时运行。所以你也应该从你的片段中传递一个回调。

标签: java android android-fragments arraylist android-volley


【解决方案1】:

不确定这是否是解决问题的理想方法,但它有效,我将回调函数移到 MainRepo 中,我的 MainRepo.java onCreateView 现在看起来像这样



 @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main_repo, container, false);
        list = view.findViewById(R.id.tv);


        PullData data = new PullData(getContext());
        data.parseMain(new VolleyCallBack() {
            @Override
            public void onSuccess(ArrayList<InformationField> info) throws JSONException {
                informationList =  info;

                customAdapter arrayAdapter = new customAdapter(getContext(), R.layout.row, informationList);
                list.setAdapter(arrayAdapter);
            }

            @Override
            public void onError(String result) throws Exception {

            }
        });


        return view;
    }

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 1970-01-01
    • 2018-11-07
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多