I have some code to parse JSON data to cardview and recycler with Volley. I want to show json data into my Fragment. I\'m getting error but I don\'t know what is causing it. Any
You can refer my following sample code. I have tested.
public class RecycleCardActivityFragment extends Fragment {
private final List<Person> mPersonList = new ArrayList<>();
public RecycleCardActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycle_card, container, false);
Context context = getActivity();
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
final RVAdapter rvAdapter = new RVAdapter(mPersonList);
recyclerView.setAdapter(rvAdapter);
RequestQueue requestQueue = Volley.newRequestQueue(context);
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) {
mPersonList.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");
}
mPersonList.add(i, person);
}
rvAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
requestQueue.add(jsonArrayRequest);
return view;
}
}
About the Person
class and RVAdapter
class, please take a look at my answer at the following question
How to load data(json) into recycler view using volley
Hope this helps!