当前位置: 首页 > 知识库问答 >
问题:

尝试从一个json对象中的两个json数组在recyclerview中填充数据时发生IndexOutOfBoundsException

李洋
2023-03-14

我从服务器获得一个Json对象,该Json对象包含两个Json数组。我知道如何将数据放入json数组中的recyclerview。但我不知道如何将两个json数组数据放入recyclerview。其中一个Json数组包含rep、name和name1。这里的name表示name1的id(codeID)。下一个数组包含customer(codeID)和coll(name和customer相同)。我使用两个不同的表生成json。我现在正在recyclerview中成功填充名称1。

我想要的是获取 name1 及其相应的 coll 值。例如,每行都需要表示 name1 和 name1 的 coll 值。某些 name1 没有 coll 值(null)。在这种情况下,coll 文本视图需要为空。有时两个数组的大小(长度)不相等。

这是我的Json。

{
  "feed": [
    {
      "rep": "503",
      "name": "30000216",
      "name1": "GERLINE TYRE HOUSE (BRANCH)"
    },
    {
      "rep": "503",
      "name": "30000217",
      "name1": "*G.L.P.K.Liyanage(ISURU ENTERP"
    },
    {
      "rep": "503",
      "name": "30000218",
      "name1": "**Kamal Motor Stores"
    },
    {
      "rep": "503",
      "name": "30000223",
      "name1": "T.Thamotherempillai & Sons"
    },
    {
      "rep": "503",
      "name": "30001037",
      "name1": "Iynkarn Motors(Distributor)"
    },
    {
      "rep": "503",
      "name": "30001074",
      "name1": "Northern Province MPCS FED"
    },
    {
      "rep": "503",
      "name": "30001131",
      "name1": "Kishor Tyre House"
    },
    {
      "rep": "503",
      "name": "45000012",
      "name1": "R.G.M.Transporters"
    }
  ],
  "feeddd": [
    {
      "customer": "30000220",
      "coll": "92820.00"
    },
    {
      "customer": "30000222",
      "coll": "1784348.61"
    },
    {
      "customer": "30000224",
      "coll": "2661442.57"
    },
    {
      "customer": "30000225",
      "coll": "15580475.00"
    },
    {
      "customer": "30001302",
      "coll": "698968.93"
    }
  ]
}

YourDealerList片段类

private void getJsonRequest() {
        progressView.start();

        final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
        Cursor cr = sqLiteHandler.getData(sqLiteHandler);
        cr.moveToFirst();

        do {
            repNo = cr.getString(0);
        } while (cr.moveToNext());
        cr.close();

        CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {


            @Override
            public void onResponse(JSONObject response) {
                progressView.stop();

                try {
                    JSONObject jsonObject = new JSONObject(String.valueOf(response));
                    if (jsonObject.names().get(0).equals("feed")) {
                        dealerList = parseJsonResponse(response);
                        dlAdapter.setDealertList(dealerList);

                        JSONArray arrayDealerColl = response.getJSONArray("feeddd");
                        ArrayList<DealerCollection> dealerColList = new ArrayList<>();
                        for (int i = 0; i < arrayDealerColl.length(); i++) {
                            JSONObject obj3 = arrayDealerColl.getJSONObject(i);
                            String dealerName = obj3.getString("customer");
                            String dealerCollection = obj3.getString("coll");

                            DealerCollection dealerColl = new DealerCollection();
                            dealerColl.setDealerName(dealerName);
                            dealerColl.setDealerCollection(dealerCollection);

                            dealerColList.add(dealerColl);
                            dlAdapter.setDealerCollectionList(dealerColList);

                        }

                    } else {
                        Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

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

            }
        }) {
            protected Map<String, String> getParams() throws AuthFailureError {
                hashMap = new HashMap<String, String>();
                hashMap.put("repNo", repNo);
                return hashMap;
            }
        };
        requestQueue.add(request);
        request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }


    private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
        ArrayList<SuggestGetSet> groupList = new ArrayList<>();
        if (response != null || response.length() > 0) {

            try {

                JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);

                for (int i = 0; i < arrayDelaers.length(); i++) {
                    JSONObject currentObject = arrayDelaers.getJSONObject(i);
                    String rep = currentObject.getString(KEY_REP_ID);
                    String name = currentObject.getString(KEY_REP_NAME);
                    String dealerId = currentObject.getString(KEY_DEALER_ID);

                    SuggestGetSet delaers = new SuggestGetSet();
                    delaers.setId(rep);
                    delaers.setName(name);
                    delaers.setDealerId(dealerId);

                    groupList.add(delaers);

                }
                //Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return groupList;
    }

我的适配器类

public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
    private LayoutInflater layoutInflater;
    public Context mcontext;
    private List<SuggestGetSet> dealerArrayList;
    private List<SuggestGetSet> originalDealerArrayList;
    private List<DealerCollection> dealerCollectionArrayList;
    Typeface type;
    private static String selectedRepId, selectedDealerId, selectedDealerName;

    public DealerListAdapter() {
    }

    public DealerListAdapter(Context context) {
        layoutInflater = LayoutInflater.from(context);
        type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
    }

    public static String getDealerName() {
        return selectedDealerName;
    }

    public static String getDealerID() {
        return selectedDealerId;
    }

    public static String getRepID() {
        return selectedRepId;
    }

    public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
        this.mcontext = context;
        layoutInflater = LayoutInflater.from(context);
        this.dealerArrayList = new ArrayList<>(dList);
        this.originalDealerArrayList = new ArrayList<>(dList);
        type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
    }

    public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
        this.dealerArrayList = dealerAList;
        originalDealerArrayList = new ArrayList<>(dealerAList);
        notifyItemRangeChanged(0, dealerArrayList.size());
    }

    public void setDealerCollectionList(ArrayList<DealerCollection> dealerColList) {
        this.dealerCollectionArrayList = dealerColList;
        notifyItemRangeChanged(0, dealerCollectionArrayList.size());
    }

    @Override
    public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
        ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
        return viewHolderDealerList;
    }

    @Override
    public void onBindViewHolder(ViewHolderDealerList holder, int position) {
        final SuggestGetSet model = dealerArrayList.get(position);
        holder.bind(model);

        final int pos = position;

        final DealerCollection model_two = dealerCollectionArrayList.get(position);
        holder.bind_two(model_two);

        holder.dealerName.setText(dealerArrayList.get(position).getName());

        holder.dealerName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectedDealerId = dealerArrayList.get(pos).getDealerId();
                selectedRepId = dealerArrayList.get(pos).getId();
                selectedDealerName = dealerArrayList.get(pos).getName();
            }
        });

        if (dealerArrayList.get(position).getDealerId() == dealerCollectionArrayList.get(position).getDealerName()) {
            holder.dealerCol.setText(dealerCollectionArrayList.get(position).getDealerCollection());
        }

    }

    @Override
    public int getItemCount() {
        return dealerArrayList.size();
    }

    static class ViewHolderDealerList extends RecyclerView.ViewHolder {
        private TextView dealerName, dealerCol;

        public ViewHolderDealerList(View itemView) {
            super(itemView);
            dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
            dealerCol = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
        }

        public void bind(SuggestGetSet model) {
            dealerName.setText(model.getName());
        }

        public void bind_two(DealerCollection model) {
            dealerCol.setText(model.getDealerCollection());
        }

    }

    public void setFilter(List<SuggestGetSet> models) {
        dealerArrayList = new ArrayList<>();
        dealerArrayList.addAll(models);
        notifyDataSetChanged();
    }

}

我的LogCat

04-29 14:06:53.529 11709-11709/com.ceatkelanisrilanka.dushanmadushanka.ceat E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
  at java.util.ArrayList.get(ArrayList.java:304)
  at com.ceatkelanisrilanka.dushanmadushanka.ceat.adapters.DealerListAdapter.onBindViewHolder(DealerListAdapter.java:83)
  at com.ceatkelanisrilanka.dushanmadushanka.ceat.adapters.DealerListAdapter.onBindViewHolder(DealerListAdapter.java:21)
  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471)
  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504)
  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741)
  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
  at android.support.v7.widget.LayoutState.next(LayoutState.java:100)
  at android.support.v7.widget.StaggeredGridLayoutManager.fill(StaggeredGridLayoutManager.java:1538)
  at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:657)
  at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:592)
  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
  at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2906)
  at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
  at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1695)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
  at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
  at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
  at android.view.View.layout(View.java:13754)
  at android.view.ViewGroup.layout(ViewGroup.java:4362)
  at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1866)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1687)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
  at android.view.Choreographer.doCallbacks(Choreographer.java:555)
  at android.view.Choreographer.doFrame(Choreographer.java:525)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
  at android.os.Handler.handleCallback(Handler.java:615)
  at android.os.Handler.dispatchMessage(Handler.java:92)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:4745)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.intern

共有1个答案

程成天
2023-03-14

请写入此条件,而不是从索引位置提取对象:

 if (dealerCollectionArrayList.size < position) {
        final DealerCollection model_two = dealerCollectionArrayList.get(position);
        holder.bind_two(model_two);

        if (dealerArrayList.get(position).getDealerId() == dealerCollectionArrayList.get(position).getDealerName()) {
            holder.dealerCol.setText(dealerCollectionArrayList.get(position).getDealerCollection());
        }
    }else {
         //Set not available or something
    }
 类似资料:
  • 问题内容: 我有2个1d数组,而我正在尝试将它们填充到JAVA中的单个2d数组中。 例如: 结果应为: 我该怎么办?我目前有这样的事情: 我有点被困在那里… 问题答案: 2D数组是数组的数组。那你为什么不试试这个呢? 为了确保它是如此简单并且可以正常工作,请进行以下测试:

  • 所以我用Java处理这些数据: 我需要将其转换为JSON: 但是我不知道怎么做。 目前我认为这是最好的方法: 但我不确定如何使用Hashmap实现这一点。我知道是这样的: 但确切的语法,以及如何将其与其他数据一起添加,我无法计算。有什么想法吗?

  • 我有一个返回JSON对象的REST方法,JSON文件大小差不多有7MB,有差不多4600个JSON对象。我无法一次将整个数据解析到recyclerView中,因为这会导致OutOfMemory异常。 我在这里面临的问题是recyclerview显示的ROLL_NUM、CURRENT_CLASS、STUDENT_NAME的值为空 示例JSON响应:{“RESTRESULT”:[{“”ROLL_NUM

  • 这里是javascript/react新手。我正试图用api中的数据从引导程序填充表。我制作了两个组件-仪表板。js和CustomTable。js,都是功能性的。就我所知,在仪表板组件上,我需要进行API调用——我已经使用useEffect和axios完成了这项工作。在桌子上。js我需要对列和数据使用useState。我想使我的表成为动态的,包括行和列。看看我的仪表板代码。js。 接下来,我得到了

  • 我得到错误:“com.google.gson.jsonSyntaxException:java.lang.IllegalStateException:Expected BEGIN_OBJECT但是BEGIN_ARRAY位于第1行column 283 path$.items.Promended[0].images” 我请求帮助从json对象提取数据。 我只需要删除类'images',并将'urls'

  • 问题内容: 这应该是程序员经常遇到的问题,但是我从来没有尝试过用这种方式来解决问题。 也就是说,我会解释。说,我需要像这样从表Zoo获取值: 现在,我可以将所有值都添加到列表中。我需要在网格中显示该查询的详细信息。现在已经有了z.predator和z.prey值(它们是时间上的整数,即它们各自的ID),我需要填充其有意义的值以将其显示给最终用户(我不能仅仅显示其ID)。所以现在我可能会做这样的事情