【问题标题】:How to load data into recyclerView如何将数据加载到recyclerView
【发布时间】:2019-08-08 11:03:27
【问题描述】:

在我的应用程序中,我想从服务器获取一些数据并显示到recyclerView。对于应用程序架构,我使用 MVP
我写了下面的代码,但是从服务器加载数据后,没有显示任何数据到recyclerView

我使用了调试模式并在这个断点中显示数据

public void add(List<DataItem> list) {
    list.addAll(list);
    notifyDataSetChanged();
}

但不向我显示recyclerView的数据!

我的活动代码:

public class ListFragment extends Fragment implements ActiveTestsContract.View {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_tester_active_tests, container, false);
        //Initialize
        init();
        //User token log
        if (!App.isEmptyString(App.getPrefs("JWT")) || !App.getPrefs("JWT").equals(ConstKeys.EMPTY)) {
            userToken = App.getPrefs("JWT");
        }
        //Load data
        getData();

        return view;
    }

    @Override
    public void updateTestsList(Data data, int page) {
        testerDashboard_emptyLay.setVisibility(View.GONE);
        activeTests_pullToLoader.setVisibility(View.VISIBLE);
        //Get lasted page
        if (page == data.getLastPage()) {
            isHasLoadedAll = true;
            activeTests_pullToLoader.setComplete();
        }
        adapter.add(data.getData());
        //Complete items
        isLoading = false;
        nextPage = page + 1;
        activeTests_pullToLoader.setComplete();
    }

    @Override
    public void init() {
        context = getActivity();
        handler = new Handler(Looper.getMainLooper());
        testsPresenter = new ActiveTestsPresenter(this, 3);
        testerDashboard_loader = view.findViewById(R.id.testerDashboard_loader);
        activeTests_pullToLoader = view.findViewById(R.id.activeTests_pullToLoader);
        testerDashboard_emptyLay = view.findViewById(R.id.testerDashboard_emptyLay);
        emptyLayout_editProfileBtn = view.findViewById(R.id.emptyLayout_editProfileBtn);
        layoutManager = new LinearLayoutManager(context);
        recyclerView = activeTests_pullToLoader.getRecyclerView();
        //Adapter
        adapter = new TesterActiveRecyclerAdapter(activeModel, context);
        //Init recycler and adapter
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        activeTests_pullToLoader.setColorSchemeResources(R.color.colorPrimary);
    }

    private void getData() {
        activeTests_pullToLoader.isLoadMoreEnabled(true);
        activeTests_pullToLoader.setPullCallback(new PullCallback() {
            @Override
            public void onLoadMore() {
                isLoading = true;
                //Call api
                testsPresenter.testsListResponse(App.recipesApi, userToken, nextPage);
            }

            @Override
            public void onRefresh() {
                adapter.clear();
                isHasLoadedAll = false;
                isLoading = true;
                //Call api
                testsPresenter.testsListResponse(App.recipesApi, userToken, 1);
            }

            @Override
            public boolean isLoading() {
                return isLoading;
            }

            @Override
            public boolean hasLoadedAllItems() {
                return isHasLoadedAll;
            }
        });
        activeTests_pullToLoader.initLoad();
    }

适配器代码:

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

    private List<DataItem> list;
    private Context context;

    public TesterActiveRecyclerAdapter(List<DataItem> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_tester_test_list, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        DataItem item = list.get(position);
        //Name
        holder.txt_name.setText(item.getTitle());
        //Conditions
        if (!App.isEmptyString(item.getOs()) && !App.isEmptyString(item.getType()) && !App.isEmptyString(item.getBrowser())) {
            holder.txt_condition.setText(item.getType() + " | " + item.getOs() + " | " + item.getBrowser());
        }
        //Button actions
        holder.setState(item.getState(), position);
        //Price
        holder.rowTests_priceTxt.setText(item.getPrice() + " Dollar");
        //Animate items
        Animation animation = AnimationUtils.loadAnimation(App.context,
                (position > list.size() - 1) ? R.anim.down_from_top : R.anim.up_from_bottom);
        holder.itemView.startAnimation(animation);

        Toast.makeText(context, ""+list.get(0).getId(), Toast.LENGTH_SHORT).show();
    }

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

    public void add(List<DataItem> list) {
        list.addAll(list);
        notifyDataSetChanged();
    }

    public void clear() {
        list.clear();
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private ViewGroup root;
        private TextView txt_name, txt_value, txt_condition, rowTests_priceTxt;
        private RoundTextView rowTests_button;

        ViewHolder(View view) {
            super(view);
            root = (ViewGroup) view;
            txt_name = view.findViewById(R.id.txtTestListTitle);
            txt_value = view.findViewById(R.id.txtTestListSublist);
            txt_condition = view.findViewById(R.id.txtTestListSublist2);
            rowTests_priceTxt = view.findViewById(R.id.rowTests_priceTxt);
            rowTests_button = view.findViewById(R.id.rowTests_button);
        }
}

我该如何解决?

【问题讨论】:

    标签: java android android-recyclerview


    【解决方案1】:

    您在参数中传递的同一list 中再次添加数据。尝试替换下面的代码

    public void add(List<DataItem> list) {
        list.addAll(list);
        notifyDataSetChanged();
    }
    

    public void add(List<DataItem> list) {
        this.list.addAll(list);
        notifyDataSetChanged();
    }
    

    【讨论】:

    • 感谢 rahul,这对我有用。但是为什么不在我上面的代码中显示数据呢?
    • @Shambooli 它不起作用,因为您正是您在函数中传递的列表,而不是适配器的列表。
    • 我在我的回答中写道,您正在将相同的列表添加到给定的参数列表中。如果有帮助别忘了接受和支持
    • @YashKrishanVerma,谢谢。但你能把你的答案发给我吗?
    • 是的,我已经添加了答案。 stackoverflow.com/a/57411329/8259771
    【解决方案2】:
    1. 清除当前列表
    2. 将数据添加到适配器的列表中。

      public void add(List<DataItem> list) {
          clear();
          this.list.addAll(list);
          notifyDataSetChanged();
      }
      

    您的方法不起作用,因为您正在更新您在函数中传递的列表,而不是适配器的列表。

    【讨论】:

    【解决方案3】:

    首先将所有数据添加到列表中,然后通知您的适配器,然后将您的适配器设置为 recyclerview。

    list.addAll(data)
    adapter.notifyDataSetChanged()
    
      val layoutManager = LinearLayoutManager(activity)
      recyclerview.isNestedScrollingEnabled = false
      recyclerview.layoutManager = layoutManager 
      recyclerview.itemAnimator = DefaultItemAnimator()
      recyclerview.adapter = mAdapter
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 2019-12-22
      相关资源
      最近更新 更多