【问题标题】:Data are not showing in the recyclerview but after turn off and turn on shows list of data数据未显示在recyclerview中,但关闭并打开后显示数据列表
【发布时间】:2017-01-06 02:23:50
【问题描述】:

我正在开发一个应用程序,我正在使用 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;
    }
}

【问题讨论】:

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


    【解决方案1】:

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

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

    我只是添加来自AllOffers.java 的重要部分。您可能在这里考虑的一件事是将网络调用与您使用 volley 保持在同一类中。当我们从服务器获得响应时,更容易在您的Adapter 上调用notifyDatasetChanged

    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。我也删除了那条线。

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2020-06-02
      • 1970-01-01
      • 2022-01-26
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 2020-10-06
      相关资源
      最近更新 更多