mostrar - recorrer objeto json javascript



Cómo cargar datos(json) en la vista de reciclado usando volley (1)

Puedes probar como mi siguiente solución:

Supongamos la respuesta del servidor como el siguiente JSON:

[
    {
        "name": "Person 1",
        "age": 30
    },
    {
        "name": "Person 2",
        "age": 20
    },
    {
        "name": "Person 3",
        "age": 40
    }
]

En tu proyecto de Android:

public class Person {
    String name;
    Integer age;

    Person() {
    }    
}


public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
    List<Person> persons;

    RVAdapter(List<Person> persons) {
        this.persons = persons;
    }

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

    @Override
    public void onBindViewHolder(PersonViewHolder holder, int position) {
        holder.personName.setText(persons.get(position).name);
        holder.personAge.setText(String.valueOf(persons.get(position).age));
    }

    @Override
    public int getItemCount() {
        if (persons != null) {
            return persons.size();
        }
        return 0;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public static class PersonViewHolder extends RecyclerView.ViewHolder {
        CardView cv;
        TextView personName;
        TextView personAge;

        PersonViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.cv);
            personName = (TextView) itemView.findViewById(R.id.person_name);
            personAge = (TextView) itemView.findViewById(R.id.person_age);
        }
    }
}

Luego en tu actividad:

        ...
        RecyclerView rv = (RecyclerView)findViewById(R.id.rv);
        rv.setHasFixedSize(true);

        LinearLayoutManager llm = new LinearLayoutManager(mContext);
        rv.setLayoutManager(llm);

        final RVAdapter rvAdapter = new RVAdapter(personList);
        rv.setAdapter(rvAdapter);

        RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        String url = "http://192.16.1.100/api/persons";

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                try {
                    if (response.length() > 0) {
                        personList.clear();
                        for (int i = 0; i < response.length(); i++) {
                            JSONObject jsonObject = response.getJSONObject(i);
                            Person person = new Person();
                            if (!jsonObject.isNull("name")) {
                                person.name = jsonObject.getString("name");
                            }
                            if (!jsonObject.isNull("age")) {
                                person.age = jsonObject.getInt("age");
                            }
                            personList.add(i, person);
                        }
                        rvAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // do something
            }
        });

        requestQueue.add(jsonArrayRequest);
        ...

Aquí está el resultado

¡Espero que esto ayude!

He implementado recyclerview en mi aplicación y ahora necesito obtener datos del servidor y acabo de enterarme de que la descarga es la mejor forma de recuperar datos. Busqué en línea, pero no puedo encontrar un tutorial adecuado para el mismo.

Así es como inicié la vista de reciclador en mi código. (Que tiene un conjunto de datos codificados)

 mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(linearLayoutManager);

    mAdapter = new CardAdapter();
    mRecyclerView.setAdapter(mAdapter);  

aquí está el código del adaptador.

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

ArrayList<BusRouteNameDetails> mItems;
public int TAG=0;

public CardAdapter() {
    super();
    mItems = new ArrayList<>();
    BusRouteNameDetails routename = new BusRouteNameDetails();
    routename.setName("xyz");
    routename.setNumber("X4");

    mItems.add(routename);

    routename = new BusRouteNameDetails();
    routename.setName("xyz");
    routename.setNumber("X4");

    mItems.add(routename);

    routename = new BusRouteNameDetails();
    routename.setName("xyz");
    routename.setNumber("X4");

    mItems.add(routename);

    routename = new BusRouteNameDetails();
    routename.setName("xyz");
    routename.setNumber("X4");

    mItems.add(routename);


    routename = new BusRouteNameDetails();
    routename.setName("xyz");
    routename.setNumber("X4");

    mItems.add(routename);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.busroutename_list, viewGroup, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    BusRouteNameDetails routename = mItems.get(i);
    viewHolder.tvName.setText(routename.getName());
    viewHolder.tvRoutename.setText(routename.getNumber());
    Log.e("TAG","i value="+ i);
    if(i==mItems.size()-1)
       viewHolder.seperator.setVisibility(View.INVISIBLE);

}

@Override
public int getItemCount() {
    Log.e("TAG","item size"+ mItems.size());
    return mItems.size();

}

class ViewHolder extends RecyclerView.ViewHolder{


    public TextView tvName;
    public TextView tvRoutename;
    public View seperator;

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

        tvName = (TextView)itemView.findViewById(R.id.RouteName1);
        tvRoutename = (TextView)itemView.findViewById(R.id.Route_src_dest);
        seperator=(View)itemView.findViewById(R.id.seperator);
    }
}
}

Y aquí están los getters y setters

public class BusRouteNameDetails {
private String mName;
private String mNumber;

public String getName() {
    return mName;
}

public void setName(String name) {
    this.mName = name;
}

public String getNumber() {
    return mNumber;
}

public void setNumber(String Number) {
    this.mNumber = Number;
}

}




android-volley