Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load data(json) into recycler view using volley

I have implemented recyclerview in my application and now i need to fetch data from the server and i just came to know about volley being the best way to fetch data. I searched online but i am unable to find a proper tutorial for the same.

This is how i initialized the recyclerview in my code.(which has hardcoded data set)

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

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

here is the adapter code.

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);
    }
}
}

And here are the getters and 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;
}

}
like image 902
Devs Avatar asked Sep 10 '15 02:09

Devs


1 Answers

You can try as my following solution:

Let's assume the server response as the following JSON:

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

In your Android project:

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);
        }
    }
}

Then in your Activity:

        ...
        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);
        ...

Here is the result

enter image description here

Hope this helps!

like image 163
BNK Avatar answered Oct 02 '22 00:10

BNK