adapter.setNotifyDatachanged()在android中没有按预期工作

时间:2016-05-19 18:16:54

标签: android

这是我的代码文件。

public class FragmentOfferList extends ListFragment {

    private RecyclerView recyclerView;
    private String TAG = FragmentOfferList.class.getSimpleName();
    private static final String endpoint = "http://example.com/offer/offers.json";
    private List<Offer> offers = new ArrayList<>();
    private ProgressDialog pDialog;
    RecyclerView.Adapter adapter;

    public FragmentOfferList() {
    }

    public static FragmentOfferList newInstance(int num) {
        FragmentOfferList f = new FragmentOfferList();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pDialog = new ProgressDialog(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.recycler_list, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new MyAdapter(offers, getActivity());
        recyclerView.setAdapter(adapter);
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {

            @Override
            public void onClick(View view, int position) {
                Offer offer = Utility.getOffers().get(position);
                Intent intent = new Intent(getActivity(), ActivityProductList.class);
                intent.putExtra("query", offer.getQuery());
                startActivity(intent);

                //startActivity(new Intent(getActivity(), ActivityProductList.class));
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));
        if (Utility.getOffers().size() == 0){
            fetchOffers();
        }
        else{
            Utility.displayToast("here");
            offers = Utility.getOffers();
            adapter.notifyDataSetChanged();
        }

        return v;
    }

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

        private List<Offer> offers;
        private Context context;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView title, year, offer;
            ImageView imageView;

            public MyViewHolder(View view) {
                super(view);
                imageView = (ImageView) view.findViewById(R.id.thumbnail);
                title = (TextView) view.findViewById(R.id.title);
                offer = (TextView) view.findViewById(R.id.offer);
            }
        }

        public MyAdapter(List<Offer> offers, Context context) {

            this.offers = offers;
            this.context = context;
        }

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

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Offer offer = offers.get(position);
            holder.title.setText(offer.getName());
            holder.offer.setText(offer.getOffer());
            Glide.with(context).load(String.valueOf(offer.getUrl()))
                    .error(R.drawable.placeholder)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(holder.imageView);
        }

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

    private void fetchOffers() {

        pDialog.setMessage("Downloading json...");
        pDialog.show();

        JsonArrayRequest req = new JsonArrayRequest(endpoint,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();

                        offers.clear();
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject object = response.getJSONObject(i);
                                Offer offer = new Offer();
                                offer.setOffer(object.getString("offer"));
                                offer.setName(object.getString("name"));
                                offer.setUrl(object.getString("url"));
                                offer.setQuery(object.getString("query"));
                                offers.add(offer);

                            } catch (JSONException e) {
                                Log.e(TAG, "Json parsing error: " + e.getMessage());
                            }
                        }

                        Utility.setOffers(offers);
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                pDialog.hide();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(req);
    }
}

当Utility.getoffers()。size()为0时,它首次获取数据,将其保存在Utility.setOffers(商品)中,并按预期显示在屏幕上。但是下次(回到同一个活动),Utility.getoffers()。size()不是0,我直接从Utility.getBrands()获得数据。

之后我调用了adapter.notifyDataSetChaned(),但它无效。即使数据大小超过0但屏幕上没有数据呈现,也不能正常工作?

这里有什么问题?我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

您没有更新offers列表,而是将其替换为适配器没有引用的其他列表。要解决此问题,您可以执行以下操作:

offers.clear();
offers.addAll(Utility.getOffers());
adapter.notifyDataSetChanged();