recyclerview在7个项目后未显示json数组中的数据

时间:2018-08-10 10:52:21

标签: android-recyclerview android-volley targetsdkversion

我正在将Recycler View与Cardview一起使用,并使用Volley显示来自JSON的数据。当targetdkversion为26时,它可以在targetdkversion 19上正常工作,但在7个列表项之后不显示数据。

            btnsend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    chatLayout.setVisibility(View.VISIBLE);
                    subject = etsub.getText().toString();
                    details = etdetail.getText().toString();
                    if (etsub.getText().toString().equals("")) {
                        Toast.makeText(getActivity(), "Enter subject", Toast.LENGTH_SHORT).show();
                        subj_layout.setError("Plese Enter Subject!");
                    }
                    else if (etdetail.getText().toString().equals("")) {
                        detail_layout.setError("Please Enter Details!");
                    }
                    else {
                        Log.d(TAG, "onClick:send ");
                        String url = "http://webapi.eduware.in/test/api/ParentsCommunication?StudentCurrentID=" + studentId.trim() + "&SchoolID=" + schoolid.trim() + "&CommunicationSubject=" + subject.trim() + "&CommunicationDetails=" + details.trim();
                        Log.d(TAG, "onClick: " + url);
                        Log.d(TAG, "fetchNotificationByVolley: url = " + url);

                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Log.d(TAG, "onResponse: " + response);
                                        try {
                                            JSONObject jobj = new JSONObject(response);
                                            String status = jobj.getString("status");
                                            if (status.equals("1")) {
                                                Toast.makeText(getActivity(), "Successfully added", Toast.LENGTH_SHORT).show();
                                                getChatbyVolley();
                                                txtnocomm.setVisibility(View.GONE);

                                            } else {
                                                Toast.makeText(getActivity(), "Data not added", Toast.LENGTH_SHORT).show();
                                                chatLayout.setVisibility(View.VISIBLE);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.d(TAG, "onErrorResponse: " + error.getMessage());
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                return null;
                            }
                        };

                        ApplicationController.getInstance().addToRequestQueue(stringRequest);

                        d.dismiss();
                    }
                }
            });

As shown in image, on click of Bottom right corner Add Button One custom dialog gets open and details of that dislogs edittext will be added to recyclerview by getChatbyVolley method.I am getting succesfully added but not display in list.But if targetsdkversion is 18 then it works perfect.

private void getChatbyVolley() {
    chatLayout.setVisibility(View.VISIBLE);
    String url = "http://webapi.eduware.in/test/api/ParentsCommunication?StudentCurrentID="+studentId.trim();
    final ArrayList<Chat> arrayList = new ArrayList<>();
    final ArrayList<String> array = new ArrayList<>();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "onResponse: " + response);
                    try {
                        JSONObject jobj = new JSONObject(response);
                        String status = jobj.getString("status");
                        if(status.equals("1"))
                        {

                            JSONArray jsonArray = jobj.getJSONArray("data");

                            for(int i=0;i<jsonArray.length();i++)
                            {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String date = jsonObject.getString("Date");
                                Log.d(TAG, "onResponse: "+date);
                                String[] separated = date.split("[T :]");
                                Log.d(TAG, "onResponse: splitted string0" + separated[0]);
                                Log.d(TAG, "onResponse: splitted string1" + separated[1]);
                                Log.d(TAG, "onResponse: splitted string2" + separated[2]);
                                Log.d(TAG, "onResponse: splitted string3" + separated[3]);
                                String time = separated[1] + ":" + separated[2];
                                Log.d(TAG, "onResponse: time is:::::::::::" + time);
                                DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
                                String inputDateStr=separated[0];
                                Date date1 = inputFormat.parse(inputDateStr);
                                String outputDateStr = outputFormat.format(date1);
                                String detail = jsonObject.getString("CommunicationDetails");
                                Log.d(TAG, "onResponse: details========="+detail);
                                String pid = jsonObject.getString("ParentID");
                                Log.d(TAG, "onResponse: pid is*********"+pid);
                                array.add(pid);
                                Log.d(TAG, "onResponse: pid is*********"+array);
                                editor.putString("parent_id",pid);
                                editor.putString("parentid_array",array.toString());
                                editor.commit();
                                Chat c = new Chat();
                                c.setCommsubject(jsonObject.getString("CommunicationSubject"));
                                c.setCommdetails(jsonObject.getString("CommunicationDetails"));
                                c.setDate(outputDateStr);
                                c.setParentid(pid);
                                arrayList.add(c);
                                progress.dismiss();

                            }
                            chatAdapter = new ChatAdapter(getActivity(), arrayList);
                            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                            recyclerView.setAdapter(chatAdapter);
                            recyclerView.setHasFixedSize(true);
                            chatAdapter.notifyDataSetChanged();

                            Log.d(TAG, "onResponse: " + arrayList.size());
                            progress.dismiss();
                        }
                        else
                        {
                            Toast.makeText(context, "No communication available", Toast.LENGTH_SHORT).show();
                            progress.dismiss();
                            rlnocomm.setVisibility(View.VISIBLE);
                            btnadd.setVisibility(View.VISIBLE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "onErrorResponse: " + error.getMessage());
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return null;
        }
    };
    ApplicationController.getInstance().addToRequestQueue(stringRequest);

}

2 个答案:

答案 0 :(得分:0)

在您的代码中添加以下行。它对我有用

recyclerview.setHasFixedSize(true);

答案 1 :(得分:0)

使用此代码并根据您的要求更改参数和输入文本以及模型类

它对我有用...

public class YourActivity extends AppCompatActivity {
    private RecyclerView recyclerview;
    private RecyclerView.LayoutManager mLayoutManager;
    private ProgressDialog pdialog;
    RequestQueue requestQueue;
    private MyCustomAdapter myCustomAdapter;
    private ArrayList<DataFarmer> dataFarmers;
    private ArrayList<Datum> datumArrayList;

    public Datum datum;
    NewInsuranceList newInsuranceList;

    Context context;
    BankInfo bankInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerview = (RecyclerView) findViewById(R.id.recycler_view_my_insurance);
        context = this;
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        recyclerview.setHasFixedSize(true);

        initToolbar();
        doNormalPostOperation();
    }


    private void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.mtoolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void doNormalPostOperation() {
        requestQueue = Volley.newRequestQueue(context);
        pdialog = new ProgressDialog(context);
        pdialog.setMessage("Loading");
        pdialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR_URL",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        pdialog.dismiss();

                        Log.e("login output", response);

                        NewInsuranceListAll newInsuranceListAll = new GsonBuilder().create().fromJson(response, NewInsuranceListAll.class);
                        datumArrayList = newInsuranceListAll.getDatumArrayList();
                        myCustomAdapter = new MyCustomAdapter(datumArrayList);
                        recyclerview.setAdapter(myCustomAdapter);


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pdialog.dismiss();
                        Toast.makeText(context, "Something went Wrong.. Please Try again..", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                HashMap<String, String> map = new HashMap<String, String>();


                map.put("id", /*"1"*/PrefUtils.getUser(context).getData().get(0).getId());
                map.put("type", "get_insurance_list");
                Log.e("para", map + "");
                return map;
            }

        };

        requestQueue.add(stringRequest);

    }


    public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {

        private ArrayList<Datum> moviesList;
        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView farmer_name, aadhar_card, insurance_id, tagging_date, txtRepost;
            public ImageView farmer_image;
            CircleImageView circleImageViewProfile;
            ProgressBar simpleProgressBar;
            public Button btnViewMore;


            public MyViewHolder(View view) {
                super(view);

                farmer_name = view.findViewById(R.id.editText_farmer_name);
                aadhar_card = view.findViewById(R.id.agent_adhar_number);
                insurance_id = view.findViewById(R.id.insurance_id);
                tagging_date = view.findViewById(R.id.editText_Tagging_Date);
                circleImageViewProfile = view.findViewById(R.id.visit_profile_image);
                btnViewMore = view.findViewById(R.id.btnViewMore);

            }

        }


        public MyCustomAdapter(ArrayList<Datum> moviesList) {
            this.moviesList = moviesList;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_my_insurance, parent, false);

            return new MyViewHolder(itemView);
        }

        public void clear() {
            int size = this.moviesList.size();
            if (size > 0) {
                for (int i = 0; i < size; i++) {
                    this.moviesList.remove(0);
                }

                this.notifyItemRangeRemoved(0, size);
            }
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {


            final Datum datum = moviesList.get(position);

            holder.farmer_name.setText(datum.getFarmerName() + "  ");
            holder.aadhar_card.setText(datum.getFarmerAdhaar() + "  ");
            holder.insurance_id.setText(datum.getInsuranceNumber() + "  ");
            holder.tagging_date.setText(datum.getTaggingDate() + "  ");
            Picasso.with(MyInsuranceActivity.this).load("URL" + datum.getFarmerPhoto() + "").placeholder(R.drawable.profile_image).into(holder.circleImageViewProfile);

            holder.btnViewMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent viewMoreIntent = new Intent(context, ViewAllDetailsActivity.class);
                    viewMoreIntent.putExtra("farmer_id", moviesList.get(position).getFarmerId() + "");
                    Log.e("parasdasdas", moviesList.get(position).getFarmerId() + "");
                    startActivity(viewMoreIntent);
                }
            });
        }

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

    }
}