2

I have the following JSON data i.e 10 objects in one array. I am fetching objects in recyclerview wihtout any error.

Now I need two things to do:

  1. I want to show next page data i.e. (next 10 records on so on) when user scroll recyclerview.
  2. I want to show total_quotes in recyclerview on every object. I am facing "LeadsMeta.getTotalQuotes()' on a null object reference" this error while showing total quotes.

I have commented that line in onBind in Adapter.

Please help me to solve these two problems. Many thanks in advance.

JSON Data

{
   "meta":{
      "code":200,
      "message":"success",
      "total_pages":247,
      "current_page":1,
      "total_items":2469,
      "total_quotes":5
   },
   "data":[
      {
         "id":"4968",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Pune",
         "name":"Shashikant ",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 21:53:38"
      },
      {
         "id":"4963",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Bangalore",
         "name":"Amani",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 20:46:03"
      },
      {
         "id":"4962",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Delhi",
         "name":"Mechanical Engineer",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 20:23:00"
      },
      {
         "id":"4961",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Mumbai",
         "name":"Ankush patil",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 20:20:20"
      },
      {
         "id":"4960",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Delhi",
         "name":"ER Vikash Thakur",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 20:17:32"
      },
      {
         "id":"4957",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Kolkata",
         "name":"Shiladitya Ghosh",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 20:09:44"
      },
      {
         "id":"4956",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Delhi",
         "name":"Vikash",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 20:08:44"
      },
      {
         "id":"4953",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Rishikesh",
         "name":"Rahul",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 19:51:17"
      },
      {
         "id":"4950",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Pune",
         "name":"Abhishek",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 19:43:27"
      },
      {
         "id":"4949",
         "topic":"Topic",
         "sub_topic":"Sub Topic",
         "city":"Chandigarh ",
         "name":"K Singh ",
         "quotes":"0",
         "credits":"10",
         "timestamp":"2021-01-05 19:40:36"
      }
   ]
}

My Fragment:

public class LeadsFragment extends Fragment {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    private static final String url = "myurl";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_leads, container, false);

        recyclerView = view.findViewById(R.id.recyclerview);

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                LeadModel leadsModelList = gson.fromJson(response, LeadModel.class);

                recyclerView.setHasFixedSize(true);
                layoutManager = new LinearLayoutManager(getActivity());
                recyclerView.setLayoutManager(layoutManager);
                LeadsAdapter leadsAdapter = new LeadsAdapter(getContext(), leadsModelList, recyclerView);
                recyclerView.setAdapter(leadsAdapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();

            }
        });

        RequestQueue queue = Volley.newRequestQueue(getContext());
        queue.add(stringRequest);

        return view;
    }
}

My Adapter:

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

    Context context;
    LeadModel leadsModelList;
    RecyclerView recyclerView;
    final View.OnClickListener onClickListener = new MyOnClickListener();

    public LeadsAdapter(Context context, LeadModel leadsModelList, RecyclerView recyclerView) {
        this.context = context;
        this.leadsModelList = leadsModelList;
        this.recyclerView = recyclerView;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView name, topic, sub_topic, city, credits, quotes;

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

            name = itemView.findViewById(R.id.tvName);
            topic = itemView.findViewById(R.id.tvTopic);
            sub_topic = itemView.findViewById(R.id.tvSubTopic);
            city = itemView.findViewById(R.id.tvLocation);
            credits = itemView.findViewById(R.id.tvCredits);
            quotes = itemView.findViewById(R.id.tvQuotes);
        }
    }

    @NonNull
    @Override
    public LeadsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.lead_card, viewGroup, false);
        view.setOnClickListener(onClickListener);
        LeadsAdapter.ViewHolder viewHolder = new LeadsAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull LeadsAdapter.ViewHolder viewHolder, int position) {

        viewHolder.name.setText(leadsModelList.getData().get(position).getName());
        viewHolder.topic.setText(leadsModelList.getData().get(position).getTopic());
        viewHolder.sub_topic.setText(leadsModelList.getData().get(position).getSubTopic());
        viewHolder.city.setText(leadsModelList.getData().get(position).getCity());
        viewHolder.credits.setText(leadsModelList.getData().get(position).getCredits()+ " Credits");
//        viewHolder.quotes.setText(leadsModelList.getData().get(position).getQuotes()+"/"+ leadsModelList.getMeta().getTotalQuotes() +" Quotes");
    }

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

        }
    }
}

Model Class:

public class LeadModel {

    @SerializedName("leadsMeta")
    @Expose
    private LeadsMeta leadsMeta;
    @SerializedName("data")
    @Expose
    private List<LeadsData> data = null;

    public LeadsMeta getMeta() {
        return leadsMeta;
    }

    public void setMeta(LeadsMeta leadsMeta) {
        this.leadsMeta = leadsMeta;
    }

    public List<LeadsData> getData() {
        return data;
    }

    public void setData(List<LeadsData> data) {
        this.data = data;
    }

}

Meta Class

public class LeadsMeta {

    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("total_pages")
    @Expose
    private Integer totalPages;
    @SerializedName("current_page")
    @Expose
    private Integer currentPage;
    @SerializedName("total_items")
    @Expose
    private Integer totalItems;
    @SerializedName("total_quotes")
    @Expose
    private Integer totalQuotes;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getTotalItems() {
        return totalItems;
    }

    public void setTotalItems(Integer totalItems) {
        this.totalItems = totalItems;
    }

    public Integer getTotalQuotes() {
        return totalQuotes;
    }

    public void setTotalQuotes(Integer totalQuotes) {
        this.totalQuotes = totalQuotes;
    }

}

Data Class

public class LeadsData {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("topic")
    @Expose
    private String topic;
    @SerializedName("sub_topic")
    @Expose
    private String subTopic;
    @SerializedName("city")
    @Expose
    private String city;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("quotes")
    @Expose
    private String quotes;
    @SerializedName("credits")
    @Expose
    private String credits;
    @SerializedName("timestamp")
    @Expose
    private String timestamp;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getSubTopic() {
        return subTopic;
    }

    public void setSubTopic(String subTopic) {
        this.subTopic = subTopic;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getName() {
        return name;
    }

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

    public String getQuotes() {
        return quotes;
    }

    public void setQuotes(String quotes) {
        this.quotes = quotes;
    }

    public String getCredits() {
        return credits;
    }

    public void setCredits(String credits) {
        this.credits = credits;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

}

3 Answers3

0

SerializedName for "meta" object should be "meta" in your LeadModel class.

public class LeadModel {
     
    //@SerializedName("leadsMeta")

    @SerializedName("meta")
    @Expose
    private LeadsMeta leadsMeta;}
androidLearner
  • 1,654
  • 1
  • 7
  • 13
0
  1. I want to show next page data

Please use recyclerView.addOnScrollListener on your recyclerview. When user scrolls and reaches the last item, you need to load more 10 items and append the list to existing list

public class LeadsFragment extends Fragment {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    private static final String url = "myurl";
    boolean isLoading = false; // For Tracking  


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ......
    ........
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

                if (!isLoading) {
                    if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == yourList.size() - 1) {
                        // Last item reached
                        loadMore(); // Note this method
                        isLoading = true;
                    }
                }

            }
        });

 private void loadMore() {
        // Make http Request
        // append the new data to LeadsData
        // notifyAdapter items changed
        // set isLoading = false
    }
  1. I am facing "LeadsMeta.getTotalQuotes()' on a null object reference"

Its because your serialized name in LeadModel should be as per your json

@SerializedName("meta")
Indra Kumar S
  • 2,818
  • 2
  • 16
  • 27
0

For your first problem:

You need to check this code. In MainActivity.java class here is a method loadMore(). In your case you need to do your API call to load 10 more items and then notify your adapter that you have new items and it will load them in your list. Thats how you can implement your recyclerview with endless items.

For 2nd problem:

You should change leadsMeta to meta in your @SerializedName. Here is your edited class:

public class LeadModel {

    @SerializedName("meta")
    @Expose
    private LeadsMeta leadsMeta;
    @SerializedName("data")
    @Expose
    private List<LeadsData> data = null;

    public LeadsMeta getMeta() {
        return leadsMeta;
    }

    public void setMeta(LeadsMeta leadsMeta) {
        this.leadsMeta = leadsMeta;
    }

    public List<LeadsData> getData() {
        return data;
    }

    public void setData(List<LeadsData> data) {
        this.data = data;
    }

}
Muhammad Zahab
  • 1,049
  • 10
  • 21
  • I am sharing [link](https://www.journaldev.com/24041/android-recyclerview-load-more-endless-scrolling) which have tutorial about the code i shared in my answer. Happy Coding :) – Muhammad Zahab Jun 11 '21 at 13:50