【问题标题】:On using swipe refresh in recyclerview my adapter is not getting data when it is refreshing在 recyclerview 中使用滑动刷新时,我的适配器在刷新时没有获取数据
【发布时间】:2016-09-27 05:33:59
【问题描述】:

我的最新片段

public class Latest extends Fragment {
private RecyclerView recyclerLatest;
private SwipeRefreshLayout swipeRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private List<LatestAdDetails> latestAdDetailsList = new ArrayList<>();
private LatestAdapter latestAdapter;
private LatestAdDetails latestAdDetails,latestAdDetails1;
private JSONObject jsonobject;
private Context context;
private String x;

public Latest() {
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View mainView=inflater.inflate(R.layout.latest_fragment,container,false);
    recyclerLatest = (RecyclerView) mainView.findViewById(R.id.recycler_latest);
    swipeRecycler= (SwipeRefreshLayout)mainView.findViewById(R.id.swipe_recycler_latest);
    mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
    recyclerLatest.setLayoutManager(mLayoutManager);
    recyclerLatest.setHasFixedSize(true);
    context = getContext();

    // url for latest add obtaining
    UrlConstants.latest_ad_obtained= UrlConstants.latest_ad+ AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+AppController.getString(getActivity().getApplicationContext(),"city_id");
    latestAdapter = new LatestAdapter(latestAdDetailsList);
    recyclerLatest.setAdapter(latestAdapter);
    latestAdd();
    swipeRecycler.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh(){refreshLatestAd();
        }
    });
    return mainView;
   }
private void refreshLatestAd() {
UrlConstants.latset_ad_refresh_obtained=UrlConstants.latest_ad_refresh+
        AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+
        AppController.getString(getActivity().getApplicationContext(),"city_id")+"/"+
        AppController.getString(getActivity().getApplicationContext(),"refresh_ad")+"/"+0;

    LatestRefreshHandler latestRefreshHandler = new LatestRefreshHandler("latestRefreshADD");
    latestRefreshHandler.executeAsStringRequest(new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("response", response);

            JSONArray jsonarray = null;
            try {
                jsonarray = new JSONArray(response);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < jsonarray.length(); i++) {
                try {
                    jsonobject = jsonarray.getJSONObject(i);

                    if (jsonobject.getString("default_photo").isEmpty()) {
                        x = UrlConstants.default_photo;
                    } else {
                        x = jsonobject.getString("default_photo");
                    }
                    Log.e("x", x);
                   latestAdapter.clear();
                    int Ad_id_refresh = jsonarray.getJSONObject(jsonarray.length()).getInt("id");
                    AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
                    latestAdDetails = new LatestAdDetails(
                            jsonobject.getInt("id"),
                            jsonobject.getInt("cityid"),
                            jsonobject.getInt("price"),
                            jsonobject.getInt("type"),
                            jsonobject.getInt("comments"),
                            jsonobject.getInt("categoryid"),
                            jsonobject.getInt("MainCategoryID"),
                            jsonobject.getInt("created"),
                            jsonobject.getInt("views"),
                            jsonobject.getString("title"),
                            jsonobject.getString("default_photo"),
                            jsonobject.getString("CityName"),
                            jsonobject.getString("CategoryName"),
                            jsonobject.getString("storeid"),
                            jsonobject.getString("currency"),
                            jsonobject.getString("description"),
                            jsonobject.getDouble("Latitude"),
                            jsonobject.getDouble("Longitude")
                    );
                    latestAdDetailsList.add(latestAdDetails);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            latestAdapter.addAll(latestAdDetailsList);
            latestAdapter.notifyDataSetChanged();
            recyclerLatest.setAdapter(latestAdapter);
            swipeRecycler.setRefreshing(false);
        }
    }, new BaseRequest.ErrorResponseCallback() {
        @Override
        public void onError(Exception exception) {

        }
    });
}



private void latestAdd() {
    LatestRequestHandler latestHandler = new LatestRequestHandler("latestADD");
    latestHandler.executeAsStringRequest(new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("response", response);

            JSONArray jsonarray = null;
            try {
                jsonarray = new JSONArray(response);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < jsonarray.length(); i++) {
                try {
                    jsonobject = jsonarray.getJSONObject(i);

                    if (jsonobject.getString("default_photo").isEmpty()) {
                        x = UrlConstants.default_photo;
                    } else {
                        x = jsonobject.getString("default_photo");
                    }
                    Log.e("x", x);
                    int Ad_id_refresh = jsonarray.getJSONObject(1).getInt("id");
                    AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
                    latestAdDetails = new LatestAdDetails(
                            jsonobject.getInt("id"),
                            jsonobject.getInt("cityid"),
                            jsonobject.getInt("price"),
                            jsonobject.getInt("type"),
                            jsonobject.getInt("comments"),
                            jsonobject.getInt("categoryid"),
                            jsonobject.getInt("MainCategoryID"),
                            jsonobject.getInt("created"),
                            jsonobject.getInt("views"),
                            jsonobject.getString("title"),
                            jsonobject.getString("default_photo"),
                            jsonobject.getString("CityName"),
                            jsonobject.getString("CategoryName"),
                            jsonobject.getString("storeid"),
                            jsonobject.getString("currency"),
                            jsonobject.getString("description"),
                            jsonobject.getDouble("Latitude"),
                            jsonobject.getDouble("Longitude")
                           );
                    latestAdDetailsList.add(latestAdDetails);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            latestAdapter.notifyDataSetChanged();

        }
    }, new BaseRequest.ErrorResponseCallback() {
        @Override
        public void onError(Exception exception) {

        }
    });
}}

我的适配器类

public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.MyViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String text;

private List<LatestAdDetails> latestAddDetailsList;

public LatestAdapter(List<LatestAdDetails> latestAddDetailsList) {
    this.latestAddDetailsList = latestAddDetailsList;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    private TextView txtTitle, txtDescription, txtCityName, txtPrice, txtCategory, txtHour, txtPhotoNo;
    private NetworkImageView imgPhoto;

    public MyViewHolder(View itemView) {
        super(itemView);
        txtTitle = (TextView) itemView.findViewById(R.id.txt_title_fad);
        txtDescription = (TextView) itemView.findViewById(R.id.description_fad);
        txtCityName = (TextView) itemView.findViewById(R.id.city_name_fad);
        txtPrice = (TextView) itemView.findViewById(R.id.price_fad);
        txtCategory = (TextView) itemView.findViewById(R.id.category_fad);
        txtHour = (TextView) itemView.findViewById(R.id.hours_fad);
        txtPhotoNo = (TextView) itemView.findViewById(R.id.txt_photo_no_fad);
        imgPhoto = (NetworkImageView) itemView.findViewById(R.id.img_photo_lod_fad);
    }
}

public void clear() {
    latestAddDetailsList.clear();
    notifyDataSetChanged();
 }// Add a list of items
public void addAll(List<LatestAdDetails> list) {
    latestAddDetailsList.addAll(list);
    notifyDataSetChanged();
}

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

@Override
public void onBindViewHolder(LatestAdapter.MyViewHolder holder, int position) {
    LatestAdDetails latestAddDetails = latestAddDetailsList.get(position);
    holder.txtTitle.setText(translate(latestAddDetails.getTitle()));
    holder.txtDescription.setText(translate(latestAddDetails.getDescription()));
    holder.txtCityName.setText(translate(latestAddDetails.getCityName()));
    holder.txtPrice.setText(Integer.toString(latestAddDetails.getPrice()));
    holder.txtCategory.setText(translate(latestAddDetails.getCategoryName()));
    holder.txtHour.setText(Integer.toString(latestAddDetails.getCreated()));
    holder.txtPhotoNo.setText(Integer.toString(0) + " photos ");
    try {
        imageLoader = VolleyHandler.getImageLoader();
    } catch (Exception e) {
        e.printStackTrace();
    }
    holder.imgPhoto.setImageUrl(latestAddDetails.getDefault_photo(), imageLoader);
}

@Override
public int getItemCount() {
    Log.e("size", String.valueOf(latestAddDetailsList.size()));
    return latestAddDetailsList.size();
}

private String translate(String myString) {

    try {
        myString = myString.replace("\n", "").replace("\r", "");
        byte[] utf8Bytes = myString.getBytes("UTF8");
        text = new String(utf8Bytes, "UTF8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return text;
}}

刷新适配器大小为零,但正确获取 json,但未添加到适配器,并且回收器视图未显示新数据,请帮助我,json 在每次滑动时提供 10 个数据,但未添加到回收站查看

【问题讨论】:

    标签: android-adapter android-recyclerview swiperefreshlayout


    【解决方案1】:

    这似乎是一个逻辑错误:

    在方法:refreshLatestAd(),删除这些行:

    latestAdapter.clear(); 
    latestAdapter.addAll(latestAdDetailsList);
    

    recyclerLatest.setAdapter(latestAdapter); // It need not be set again.
    

    如果有帮助,请告诉我。

    latestAdapter.notifyDataSetChanged() 足以通知 数据更改的适配器。总是修改列表 [latestAdDetailsList] 设置为适配器,这是肯定的 调用 notifyDataSetChanged 时反映更改的拍摄方式。

    【讨论】:

    • 那么新刷新的数据和旧数据如何在 Recycler 适配器中显示
    • 您已经将您的适配器列表设置为 latestAdDetailsList,因为您已经添加了从 api 调用获取的数据,因此无需重置列表,只需调用 notifyDataSetChanged(); Adapter基本上已经有了对列表的引用,所以调用notifyDataSetChanged(),这就是adapter的工作方式。
    猜你喜欢
    • 2020-03-16
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多