Search code examples
androidandroid-recyclerviewadapter

how can update date from adapter to recyclerView?


when I send new data or update the info, how can to change my recycle view?

I have used a dapter.notifyDataSetChanged(); , but it's not working...

I tried more method, but it all cannot change my recycler view

in my code

 recyclerView =  view.findViewById(R.id.recyclerCoin);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        listCoinDiamondModel = new ArrayList<>();
        requestQueue = Volley.newRequestQueue(getActivity());
        getData();
        adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
        recyclerView.setAdapter(adapter);

private void sendGift(String postUserID) {
        final String postUserIDD = postUserID;
        final String GiftAmount = this.GiftAmount.getText().toString().trim();
        final String flag = "1";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_GIFTCOIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            if (success.equals("1")){
                                adapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(),"Error" + error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                //Log.d("FID", fid);
                params.put("fid", fid);
                params.put("GiftAmount", GiftAmount);
                params.put("flag", flag);
                params.put("postUserID", postUserIDD);
                params.put("uid", getID);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }


    private JsonArrayRequest getDataFromServer(int requestCount) {
        //Initializing ProgressBar
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Load...");
        progressDialog.dismiss();
        final String GROUP_LIST = "https://example.com/aaa.php?flag=1&fid="+ getActivity().getIntent().getStringExtra("fid") +"&page="+requestCount;
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GROUP_LIST,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        parseData(response);
                        progressDialog.dismiss();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();

                        Toast.makeText(getActivity(), "No More gift Available", Toast.LENGTH_SHORT).show();
                    }
                });

        //Returning the request
        return jsonArrayRequest;
    }

    //This method will get data from the web api
    private void getData() {
        requestQueue.add(getDataFromServer(requestCount));
        requestCount++;
    }

    //This method will parse json data
    private void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            //Creating the newFeedModel object

            final CoinDiamondModel coinDiamondModel = new CoinDiamondModel();
            JSONObject json = null;
            try {
                //Getting json
                json = array.getJSONObject(i);

                String TAG_Coin = "Coin";
                String TAG_Diamond = "Diamond";
                String TAG_UserName = "UserName";
                String TAG_UserPhoto = "UserPhoto";
                String TAG_UserID = "UserID";

                //Log.d("NAME111", json.getString(json.getString(TAG_UserName)));
                coinDiamondModel.setCoin(json.getString(TAG_Coin));
                coinDiamondModel.setDiamond(json.getString(TAG_Diamond));
                coinDiamondModel.setGiftFromUserName(json.getString(TAG_UserName));
                coinDiamondModel.setGiftFromUserPhoto(json.getString(TAG_UserPhoto));
                coinDiamondModel.setGiftFromUserID(json.getString(TAG_UserID));

            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding the newFeedModel object to the list
            listCoinDiamondModel.add(coinDiamondModel);
            //adapter.addTheCoinData(coinDiamondModel);
        }

        //Notifying the adapter that data has been added or changed
        adapter.notifyDataSetChanged();
    }

who knows what's happen and how can solve this?

could you told me how can I do, please?

adapter all code

public class CoinAdapter extends RecyclerView.Adapter<CoinAdapter.ViewHolder> {
    private ImageLoader imageLoader;
    private List<CoinDiamondModel> newcoinDiamondLists;
    private RequestManager glide;
    private Context context;
    SessionManager sessionManager;
    private String getID,memail;

    public CoinAdapter(List<CoinDiamondModel> newcoinDiamondLists, Context context) {
        this.newcoinDiamondLists = newcoinDiamondLists;
        this.glide = Glide.with(context);
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.coinlist, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);

        sessionManager = new SessionManager(getApplicationContext());
        sessionManager.checkLogin();
        HashMap<String, String> user = sessionManager.getUserDetail();
        getID = user.get(sessionManager.USERID);
        memail = user.get(sessionManager.EMAIL);

        //String gid = getIntent.getStringExtra("xxx");


        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        CoinDiamondModel newCoinDiamondModel = newcoinDiamondLists.get(position);
        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();

        holder.userName.setText(newCoinDiamondModel.getGiftFromUserName());
        holder.userID.setText(newCoinDiamondModel.getGiftFromUserID());
        holder.coinCount.setText(" x "+newCoinDiamondModel.getCoin());
        glide.load(newCoinDiamondModel.getGiftFromUserPhoto()).into(holder.userPhoto);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        CircleImageView userPhoto;
        TextView userName,userID,coinCount;
        ImageView coinImg;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            userPhoto = (CircleImageView) itemView.findViewById(R.id.userPhoto);
            userName = (TextView) itemView.findViewById(R.id.userName);
            coinCount = (TextView) itemView.findViewById(R.id.coinCount);
            userID = (TextView) itemView.findViewById(R.id.userID);
            coinImg = (ImageView) itemView.findViewById(R.id.coinImg);
        }
    }

    public void addTheCoinData(CoinDiamondModel coinDiamondModel){
        if(coinDiamondModel!=null){
            newcoinDiamondLists.add(coinDiamondModel);
            notifyDataSetChanged();
        }else {
            throw new IllegalArgumentException("無資料!");
        }

    }
}

Solution

  • The RecyclerView initialization and notifyDataSetChanged() is used properly. As your question is not clear enough about the Adapter implementation of the RecyclerView, I can give you several suggestions to check.

    1. In RecyclerView.Adapter check if getItemCount() method is properly overriden with returning the list length (not 0) like below:
    @Override  
    public int getItemCount() {  
        return listdata.length;  
    }
    
    1. In RecyclerView.Adapter check if onCreateViewHolder method is properly overriden with proper xml layout like below:
    @Override  
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());  
        View listItem= layoutInflater.inflate(R.layout.coin_xml_layout, parent, false);  
        ViewHolder viewHolder = new ViewHolder(listItem);  
        return viewHolder;  
    }
    
    1. In RecyclerView.Adapter check if RecyclerView.ViewHolder class is properly extended and linked the UI elements from the xml with the adapter like below:
    public static class ViewHolder extends RecyclerView.ViewHolder {  
        public TextView coinTextView;  
        public ViewHolder(View itemView) {  
            super(itemView);  
            this.coinTextView = (TextView) itemView.findViewById(R.id.coinTextView);    
        }  
    }
    
    1. In RecyclerView.Adapter check if onBindViewHolder method is properly overridden and updated the list component UI properly like below:
      @Override  
      public void onBindViewHolder(ViewHolder holder, int position) {  
            final MyListData myListData = listdata[position];  
            holder.cointTextView.setText(listdata[position].getCoin());  
        }
    
    1. Debug with a breakpoint and check if the listCoinDiamondModel.add(coinDiamondModel) is calling or not and coinDiamondModel object is not empty.
    2. The RecyclerView is placed properly in the activity xml, like the RecyclerView is Visible, has a decent size to show list elements. As an example:
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:scrollbars="vertical"