数据未显示在recyclerview中,但在关闭和打开后显示数据列表

时间:2016-08-29 23:29:11

标签: listview android-recyclerview android-volley android-adapter

我正在开发一个应用程序,我正在使用volley库从服务器获取数据并显示在RecyclerView中。这里我使用了四个标签。

问题在于首先通过从服务器获取数据来显示要显示的元素列表,数据加载并添加到列表中,但RecyclerView从不显示它。当我关闭显示屏并将其关闭时,数据会列在RecyclerView

有人请帮帮我吗?

此处MyAdapter.java

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

private ImageLoader mImageLoader;
private Context context;

ArrayList<Coupon> couponArrayList = new ArrayList<>();

public MyAdapter(Context context,ArrayList<Coupon> couponArrayList)
{
    this.couponArrayList=couponArrayList;
    this.context=context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.offer_row,parent,false);
    ViewHolder viewHolder = new ViewHolder(view);

    viewHolder.relativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView redUrl = (TextView)view.findViewById(R.id.offer_url);
            String postUrl = redUrl.getText().toString();
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(postUrl));
            Intent browserChooserIntent = Intent.createChooser(intent , "Choose browser of your choice");
            context.startActivity(browserChooserIntent);
        }
    });

    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Coupon coupon = couponArrayList.get(position);
    holder.title.setText(coupon.getTitle());
    holder.name.setText(coupon.getName());
    holder.coupon.setText(coupon.getCoupon());
    holder.expiry.setText(coupon.getExpiry());
    holder.url.setText(coupon.getLink());

    //Image loading using singleton class
    mImageLoader = MySingleton.getInstance(context).getImageLoader();
    holder.image.setImageUrl(coupon.getImage(),mImageLoader);
    holder.image.setDefaultImageResId(R.drawable.placeholder_image);
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}
public void remove(ContactsContract.Contacts.Data data) {
    int position = couponArrayList.indexOf(data);
    couponArrayList.remove(position);
    notifyItemRemoved(position);
}

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

public static class ViewHolder extends RecyclerView.ViewHolder{
    NetworkImageView image;
    RelativeLayout relativeLayout;
    TextView title,name,coupon,expiry,url;

    public ViewHolder(View itemView) {
        super(itemView);
        this.image = (NetworkImageView)itemView.findViewById(R.id.offer_image);
        this.title = (TextView)itemView.findViewById(R.id.offer_title);
        this.name = (TextView)itemView.findViewById(R.id.offer_name);
        this.coupon = (TextView)itemView.findViewById(R.id.coupon_code);
        this.expiry = (TextView)itemView.findViewById(R.id.expiry_date);
        this.url = (TextView)itemView.findViewById(R.id.offer_url);
        this.relativeLayout = (RelativeLayout)itemView.findViewById(R.id.relLayout);

        //make sure it is clickable
        itemView.setClickable(true);
    }
}

此处AllOffers.java(Tab1)

public class AllOffers extends Fragment {
    RequestQueue queue;
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<Coupon> arrayList = new ArrayList<>();

    public AllOffers() {
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.alloffers, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        //creating object of BgT to get arraylist og offers & coupons &&asign to local arrayList
        BackgroundTask backgroundTask = new BackgroundTask(getActivity());
        arrayList = backgroundTask.getList();
        adapter = new MyAdapter(getContext(), arrayList);

        //adding horizontal line b/w  rows
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));

        recyclerView.setAdapter(adapter);
        // adapter.clearAdapter();
        arrayList.clear();

        return view;
    }
}

最后是Backgroundtask.java

public class BackgroundTask {
    Context context;
    RequestQueue queue;
    public static final String KEY_TITLE="coupon_title";
    public static final String KEY_NAME="offer_name";
    public static final String KEY_CODE="coupon_code";
    public static final String KEY_IMAGE="store_image";
    public static final String KEY_EXPIRY="coupon_expiry";
    public static final String KEY_POSTURL="store_link";

    private ImageLoader mImageLoader;
    ArrayList<Coupon> arrayList = new ArrayList<>();
    public static final String json_url="https://tools.vcommission.com/api/coupons.php?apikey=xxxxxxxxxx";

    public BackgroundTask(Context context) {
        this.context = context;
    }

    public ArrayList<Coupon> getList()
    {
        final JsonArrayRequest  jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, json_url,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        int count=0;
                        while (count<response.length())
                        {
                            try {
                                JSONObject jsonObject= response.getJSONObject(count);
                                Coupon coupon = new Coupon(jsonObject.getString(KEY_TITLE),
                                        jsonObject.getString(KEY_NAME),
                                        jsonObject.getString(KEY_CODE),
                                        jsonObject.getString(KEY_IMAGE),
                                        jsonObject.getString(KEY_EXPIRY),
                                        jsonObject.getString(KEY_POSTURL));

                                arrayList.add(coupon);
                                count++;

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context,"No internet connection...!!!",Toast.LENGTH_LONG).show();
                error.printStackTrace();
            }
        });
        MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);

        return arrayList;
    }
}

1 个答案:

答案 0 :(得分:0)

第二次正确加载了RecyclerView。所以适配器没有问题。

问题出在收到服务器的响应后,您未在notifyDatasetChanged上调用Adapter。你还有其他一些基本问题。我正在尝试修改您的代码,以便您更容易理解问题。

我只是添加AllOffers.java的基本部分。您可以在这里考虑的一件事是将网络呼叫保持在与您使用齐射相同的类中。当我们从服务器获得响应时,更容易在notifyDatasetChanged上调用Adapter

public class AllOffers extends Fragment {
    RequestQueue queue;
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<Coupon> arrayList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.alloffers, container, false);

        // Setup your RecyclerView here
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));

        // Set the adapter before the network call
        adapter = new MyAdapter(getContext(), arrayList);
        recyclerView.setAdapter(adapter);

        // Move network call here
        final JsonArrayRequest  jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, json_url,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        int count=0;
                        while (count<response.length())
                        {
                            try {
                                JSONObject jsonObject= response.getJSONObject(count);
                                Coupon coupon = new Coupon(jsonObject.getString(KEY_TITLE),
                                        jsonObject.getString(KEY_NAME),
                                        jsonObject.getString(KEY_CODE),
                                        jsonObject.getString(KEY_IMAGE),
                                        jsonObject.getString(KEY_EXPIRY),
                                        jsonObject.getString(KEY_POSTURL));

                                arrayList.add(coupon);
                                count++;

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

                        // Call notifyDatasetChanged on adapter so that the newly added items in the list takes effect in your RecyclerView
                        adapter.notifyDatasetChanged();

                    }
                }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                Toast.makeText(context,"No internet connection...!!!",Toast.LENGTH_LONG).show();
                error.printStackTrace();
            }
        });

        return view;
    }
}

您无需清除arrayList。我也删除了这一行。