Recyclerview with JSON analysis

Asked

Viewed 134 times

0

My PHP code generates the following JSON:

{
"resposta":[
    {
     "cd_servico":"1",
     "ds_servico":"NOME SERVICO",
     "ITEMS":[
        {
          "ds_descricao1":"DESCRICAO SERVICO",
          "ds_descricao2":"DESCRICAO 2",
          "ds_valor":"120.00"
        },
        {
          "ds_descricao1":"DESCRICAO SERVICO",
          "ds_descricao2":"DESCRICAO 2",
          "ds_valor":"65.00"
        }
        ]
    },
    {
      "cd_servico":"2",
      "ds_servico":"SERVICO CATEGORIA 2",
      "ITEMS":[
          {
            "ds_descricao1":"DESCRICAO",
            "ds_descricao2":"DESCRICAO",
            "ds_valor":"90.00"
           }
           ]
      }
  ]

}

I’m trying to read this file and list the items in one recyclerview, but without success.

Follows my code:

Mainactivity.java

StringRequest stringRequest = new StringRequest(Request.Method.POST,
            Connect.URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray array = jsonObject.getJSONArray("ITEMS");

                        for (int i = 0; i < array.length(); i++) {
                            JSONObject o = array.getJSONObject(i);
                            ListItem_Result_Parceiro item = new ListItem_Result_Parceiro(
                                    o.getString("cd_servico"),
                                    o.getString("ds_servico"),
                                    o.getString("ds_descricao1"),
                                    o.getString("ds_descricao2"),
                                    o.getString("ds_valor")
                            );
                            listItems.add(item);
                        }
                        adapter = new Adapter_Result_Parceiro(listItems, ResultParceiroFrag1.this.getContext());
                        recyclerView.setAdapter(adapter);
                        RecyclerSectionItemDecoration sectionItemDecoration =
                                new RecyclerSectionItemDecoration(getResources()
                                        .getDimensionPixelSize(R.dimen.header_recyclerview),
                                        true,
                                        getSectionCallback(listItems));
                        recyclerView.addItemDecoration(sectionItemDecoration);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(ResultParceiroFrag1.this.getContext(), "Sem conexão com a internet", Toast.LENGTH_LONG).show();
                }
            }
    ) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("cd_parceiro", "1");
            params.put("app_chave", chave);//
            return params;
        }
    };//Acão acima envia um post para a url (Somente tipo String)////

    RequestQueue requesQueue = Volley.newRequestQueue(ResultParceiroFrag1.this.getContext());
    requesQueue.add(stringRequest);

Java adapter.

private List<ListItem_Result_Parceiro> listItems;
private Context context;

public Adapter_Result_Parceiro(List<ListItem_Result_Parceiro> listItems, Context context) {
    this.listItems = listItems;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.result_parceiro_frag1_list_item, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ListItem_Result_Parceiro listItem = listItems.get(position);

    holder.HeadFrag1Parceiro.setText(listItem.getDs_descricao1());
    holder.DescFrag1Parceiro.setText(listItem.getDs_descricao2());
    holder.txtValorServ.setText("R$ "+listItem.getDs_valor());

}

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

public class ViewHolder extends RecyclerView.ViewHolder{

    public TextView HeadFrag1Parceiro, DescFrag1Parceiro, txtValorServ;
    public LinearLayout LinearLayout;

    public ViewHolder(View itemView) {
        super(itemView);

        HeadFrag1Parceiro      = (TextView) itemView.findViewById(R.id.HeadFrag1Parceiro);
        DescFrag1Parceiro     = (TextView) itemView.findViewById(R.id.DescFrag1Parceiro);
        txtValorServ     = (TextView) itemView.findViewById(R.id.txtValorServ);
        LinearLayout            = itemView.findViewById(R.id.linearFrag1Parceiro);
    }
}

Listitem.java

public class ListItem_Result_Parceiro {

private String cd_servico;
private String ds_servico;
private String ds_descricao1;
private String ds_descricao2;
private String ds_valor;

public ListItem_Result_Parceiro(String cd_servico, String ds_servico, String ds_descricao1, String ds_descricao2, String ds_valor) {
    this.cd_servico = cd_servico;
    this.ds_servico = ds_servico;
    this.ds_descricao1 = ds_descricao1;
    this.ds_descricao2 = ds_descricao2;
    this.ds_valor = ds_valor;
}

public String getCd_servico() {
    return cd_servico;
}

public String getDs_servico() {
    return ds_servico;
}

public String getDs_descricao1() {
    return ds_descricao1;
}

public String getDs_descricao2() {
    return ds_descricao2;
}

public String getDs_valor() {
    return ds_valor;
}

}

I checked several examples but could not find the solution.

Thanks in advance for the help of friends.

  • If possible exchange the image for the code.

  • Any specific exception or error?

  • @Caiqueromero edited the image by code.

  • @Maxfratane, I believe the problem is in reading the "ITEMS", because if I modify in php to generate the json as follows: { "answer":[{ "cd_servico":"1", "ds_servico":"SERVICO NAME"}]}, it works well...

1 answer

0


Your problem is reading the JSON. You are considering the array ITEMS is in the first object of the hierarchy, when in fact it is in the second.

JSONObject jsonObject = new JSONObject(response);

JSONArray resposta = jsonObject.getJSONArray("resposta");
for (int i = 0; i < resposta.length(); i++) {

  JSONObject object = resposta.getJSONObject(i);
  JSONArray items = object.getJSONArray("ITEMS");
  for (int j = 0; j < items.length(); j++) {
    JSONObject o = items.getJSONObject(j);
    ListItem_Result_Parceiro item = new ListItem_Result_Parceiro(
        o.getString("cd_servico"),
        o.getString("ds_servico"),
        o.getString("ds_descricao1"),
        o.getString("ds_descricao2"),
        o.getString("ds_valor")
    );
    listItems.add(item);
  }
}

I recommend you study libraries for JSON conversion, such as Gson and Moshi. With them you can convert JSON objects to Pojos, making your work easier and avoiding this kind of confusion.

  • Thanks for the tip Leonardo, the code you posted works if I remove the "cd_servico" and "ds_descricao" items that in the case are outside the "ITEMS" array, this "ds_descricao" item I wanted to be the header in the recyclerview of the items that are inside the "ITEMS" array".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.