如何在 Android Recyclerview 中显示 JSON 数组中包含的 JSON 对象

Posted

技术标签:

【中文标题】如何在 Android Recyclerview 中显示 JSON 数组中包含的 JSON 对象【英文标题】:How to show JSON objects included in JSON Array in Android Recyclerview 【发布时间】:2021-08-28 08:33:14 【问题描述】:

我有以下 JSON 数据,即一个数组中有 10 个对象。我在 recyclerview 中获取对象,没有任何错误。

现在我需要做两件事:

    我想在用户滚动 recyclerview 时显示下一页数据,即(接下来的 10 条记录,依此类推)。 我想在recyclerview 中显示每个对象的total_quotes。我在显示总引号时遇到“LeadsMeta.getTotalQuotes()' on a null object reference”这个错误。

我已经在 Adapter 的 onBind 中注释了该行。

请帮我解决这两个问题。非常感谢。

JSON 数据


   "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"
      
   ]

我的片段:

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;
    

我的适配器:

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

        
    

模型类:

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;
    


元类

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;
    


数据类

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;
    


【问题讨论】:

【参考方案1】:

“元”对象的序列化名称在您的 LeadModel 类中应该是“元”。

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

    @SerializedName("meta")
    @Expose
    private LeadsMeta leadsMeta;

【讨论】:

【参考方案2】:
    我想显示下一页数据

请在您的回收站视图中使用recyclerView.addOnScrollListener。当用户滚动并到达最后一项时,您需要加载更多 10 项并将列表附加到现有列表中

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
    
    我在空对象引用上面临“LeadsMeta.getTotalQuotes()'”

这是因为您在 LeadModel 中的序列化名称应该与您的 json 一致

@SerializedName("meta")

【讨论】:

我在@SerializedName("meta") 名称中犯了一个多么愚蠢的错误......谢谢。 完成所有事情。但有一点不清楚。如何附加数据并通知适配器 // 将新数据附加到 LeadsData // notifyAdapter 项目已更改【参考方案3】:

第一个问题:

您需要检查this 代码。在 MainActivity.java 类中,这里有一个方法 loadMore()。在您的情况下,您需要进行 API 调用以加载 10 个以上的项目,然后通知您的适配器您有新项目,它会将它们加载到您的列表中。这就是你如何使用无穷无尽的项目来实现你的recyclerview。

第二个问题:

您应该将 @SerializedName 中的 leadsMeta 更改为 meta。 这是您编辑的课程:

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;
    


【讨论】:

我正在分享link,其中有关于我在答案中分享的代码的教程。快乐编码:)

以上是关于如何在 Android Recyclerview 中显示 JSON 数组中包含的 JSON 对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android Studio 中禁用 recyclerview 特定数据?

如何在 Android 的 RecyclerView 中显示来自 Firestore 的数据?

如何在 recyclerview 适配器中将动态视图添加到 android 布局

如何在android中排列RecyclerView上的数据?

如何在android的recyclerview中搜索数据

如何在 Android Studio 中同时从 recyclerview 和数据库中删除数据? [关闭]