简体   繁体   English

如何将日期从适配器更新到 recyclerView?

[英]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();我使用了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("無資料!");
        }

    }
}

you can again set the adapter to recycler view after the response of the server您可以在服务器响应后再次将适配器设置为回收站视图

   public void onResponse(JSONArray response) {
                    parseData(response);
                    progressDialog.dismiss();
                    adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
                    recyclerView.setAdapter(adapter);
                }

solution 2: in your adapter write a function to update you list and call function in activity解决方案 2:在您的适配器中编写一个函数来更新您的列表并在活动中调用函数

add this function to the adapter将此功能添加到适配器

    public void updateList(List<CoinDiamondModel> list){
    newcoinDiamondLists = list;
    notifyDataSetChanged();
     }

and call a function updateList of when you need an update recyclerview并在您需要更新 recyclerview 时调用函数updateList

The RecyclerView initialization and notifyDataSetChanged() is used properly. RecyclerView 初始化和notifyDataSetChanged()使用得当。 As your question is not clear enough about the Adapter implementation of the RecyclerView, I can give you several suggestions to check.由于您的问题对 RecyclerView 的 Adapter 实现不够清楚,我可以给您几个建议以供检查。

  1. In RecyclerView.Adapter check if getItemCount() method is properly overriden with returning the list length (not 0) like below:RecyclerView.Adapter检查getItemCount()方法是否正确覆盖并返回列表长度(不是 0),如下所示:
 @Override public int getItemCount() { return listdata.length; }
  1. In RecyclerView.Adapter check if onCreateViewHolder method is properly overriden with proper xml layout like below:RecyclerView.Adapter检查onCreateViewHolder方法是否被正确的 xml 布局正确覆盖,如下所示:
 @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:RecyclerView.Adapter检查RecyclerView.ViewHolder类是否正确扩展并将 xml 中的 UI 元素与适配器链接,如下所示:
 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:RecyclerView.Adapter检查onBindViewHolder方法是否被正确覆盖并正确更新列表组件 UI,如下所示:
 @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.使用断点进行调试并检查listCoinDiamondModel.add(coinDiamondModel)是否正在调用并且coinDiamondModel对象不为空。
  2. The RecyclerView is placed properly in the activity xml, like the RecyclerView is Visible, has a decent size to show list elements. RecyclerView 被正确地放置在活动 xml 中,就像 RecyclerView 是可见的一样,有一个合适的大小来显示列表元素。 As an example:举个例子:
 android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical"

you can update your adapter list manually like this:(write this function in your adapter)你可以像这样手动更新你的适配器列表:(在你的适配器中写这个函数)

public void updateCoinAdapterList(ArrayList<listCoinDiamondModel> recyclerItemsList) {
        this.recyclerItemsList = recyclerItemsList;
        this.notifyDataSetChanged();
    }

you must set your adapter global variable and initialize it in OnCreate or OnResume, and call您必须设置您的适配器全局变量并在 OnCreate 或 OnResume 中对其进行初始化,然后调用

adapter.updateCoinAdapterList(listCoinDiamondModel);

when your list changed当你的名单改变时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM