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

1

5

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

}
Isobelisocheim answered 10/9, 2015 at 2:15 Comment(0)
A
15

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!

Astronavigation answered 10/9, 2015 at 3:13 Comment(21)
Can you tell me how to pass parameters?Isobelisocheim
As in need to send some values to the server. The code works fine. thank you very much,Isobelisocheim
Can you post it with parameter passing?Isobelisocheim
Can you clarify that? In my code, simple logic is: just need to make a GET request, then get the reponse and update the recycleView dataAstronavigation
i want to send latitude and longitude in the url, like using hashmap and read that on the server and run query and then feed the data backIsobelisocheim
Ah, that means send body with Volley POST Request, you can refer my answer here or alot of sample code available in SOAstronavigation
For GET request with parameters, you can see https://mcmap.net/q/236851/-volley-post-get-parameters or gist.github.com/mstfldmr/f6594b2337e3633673e5Astronavigation
Where is this personList initialize?Jaela
@RoCk you can init that list at the beginning inside onCreate() for example or when declaring it. And pay attention to "personList.clear();"Astronavigation
@Astronavigation - I init it as global. Why .clear() if in the first place it has no value? I'm Doing this on Fragment. in onCreateView.Jaela
@RoCk of course you don't have to call personList.clear();. This method only to make sure the data not duplicated every time a request executedAstronavigation
@Astronavigation - Can you help me if you have time. Do you have a sample code for PHP for this one? Only for Array - response.Jaela
@RoCk unfortunately I am not familiar with PHP, I often use ASP.NET Web API for web serviceAstronavigation
@Astronavigation - It's ok. :) .Jaela
When i switch b/w different apps and again back to app, and i scroll it then it shows items overlap why kindly tell me?Lewie
@AsadMukhtar do you mean duplicated items? If so, have you used personList.clear();?Astronavigation
yes when i switch b/w different application it shows one cardview items overlap last cardview items.Lewie
i place a framelayout and on runtime it shows cards inside it from json, json parsing is done in StartActivity and maintain a list, on fragment i pass list as a parameter and in fragment oncreate i just created the adapter and set it recyclerview, i am stuck on that why it overlaps my recyclerview items. @AstronavigationLewie
@AsadMukhtar I think you should create a new question with more details about your issue (including your code) so that everybody can helpAstronavigation
But the developers community flag it to say that it is duplicate question?Lewie
@AsadMukhtar perhaps it's not, if you make sure your issue is not the same as this question.Astronavigation

© 2022 - 2024 — McMap. All rights reserved.