如何在Recyclerview中更新数据?

时间:2018-08-18 01:50:11

标签: java android retrofit

我构建了一个将Retrofit加载数据到recyclerview的应用程序,我的recyclerview完美地加载了JSON文件中的所有数据,但是当我尝试使用swipeRefreshLayout进行更新时,我又打算再次加载方法loadFirstPage();,但只需再次添加相同的数据即可。

我在google中搜索任何解决方案,但我的所有意图均不适用于我的代码。

我打算使用adapter.clear并再次加载,但不能正常工作。

想法是,如果JSON文件中的一项发生更改,请再次更新Recyclerview中的数据。

public class historial extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    User user = SharedPrefManager.getInstance(this).getUser();

    private static final String TAG = "MainActivity";

    PaginationAdapter adapter;
    LinearLayoutManager linearLayoutManager;
    private SwipeRefreshLayout swipeRefreshLayout;
    RecyclerView recyclerView;
    ProgressBar progressBar;

    private static final int PAGE_START = 1;
    private boolean isLoading = false;
    private boolean isLastPage = false;
    // limiting to 5 for this tutorial, since total pages in actual API is very large. Feel free to modify.
    private int TOTAL_PAGES = 5;
    private int currentPage = PAGE_START;

    private NetworkInterface geosInterface;
    int position;




    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.historial);

        Toolbar toolbar = findViewById(R.id.toolbar);
        //setting the title
        toolbar.setTitle("elGEos School - Historial");
        //placing toolbar in place of actionbar
        setSupportActionBar(toolbar);

        progressBar =  findViewById(R.id.progressBar);
        recyclerView = findViewById(R.id.recycler_view);

        adapter = new PaginationAdapter(this);

        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(historial.this);

        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
            @Override
            protected void loadMoreItems() {
                isLoading = true;
                currentPage += 1;

                // mocking network delay for API call
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadNextPage();
                    }
                }, 1000);
            }

            @Override
            public int getTotalPageCount() {
                return TOTAL_PAGES;
            }

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

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

        //init serecyclerViewice and load data
        geosInterface = NetworkApi.getClient().create(NetworkInterface.class);

        loadFirstPage();


        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                //CODE FOR UPDATE HERE ???

                if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);  // This hides the spinner
                }
            }
        });

    }

    //TOOL BAR Y MENU
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu3, menu);
        return true;

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){
            case R.id.aboutback:

                onBackPressed();

                //Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
                break;



        }
        return true;
    }



    private void loadFirstPage() {
        swipeRefreshLayout.setRefreshing(true);

        Log.d(TAG, "loadFirstPage: ");

        callTopMessage().enqueue(new Callback<TopMessage>() {
            @Override
            public void onResponse(Call<TopMessage> call, Response<TopMessage> response) {
                // Got data. Send it to adapter
                                List<Result> results = fetchResults(response);
                progressBar.setVisibility(View.GONE);
                adapter.addAll(results);

                if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
                else isLastPage = true;
                swipeRefreshLayout.setRefreshing(false);

            }

            @Override
            public void onFailure(Call<TopMessage> call, Throwable t) {
                t.printStackTrace();
                // TODO: 08/11/16 handle failure
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    /**
     * @param response extracts List<{@link Result>} from response
     * @return
     */
    private List<Result> fetchResults(Response<TopMessage> response) {
        TopMessage topMessage = response.body();
        return topMessage.getResults();
    }

    private void loadNextPage() {
        swipeRefreshLayout.setRefreshing(true);

        Log.d(TAG, "loadNextPage: " + currentPage);

        callTopMessage().enqueue(new Callback<TopMessage>() {
            @Override
            public void onResponse(Call<TopMessage> call, Response<TopMessage> response) {
                adapter.removeLoadingFooter();
                isLoading = false;

                List<Result> results = fetchResults(response);
                adapter.addAll(results);

                if (currentPage != TOTAL_PAGES) adapter.addLoadingFooter();
                else isLastPage = true;
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<TopMessage> call, Throwable t) {
                t.printStackTrace();
                // TODO: 08/11/16 handle failure
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private Call<TopMessage> callTopMessage() {
        return geosInterface.getTopMessage(
                "Comfama",
                "B",
                "TTY651",
                "1",
                currentPage
        );
    }


    @Override
    public void onRefresh() {

    }
}

1 个答案:

答案 0 :(得分:1)

尝试一下:

在回收者视图中更新和删除数据非常简单

  • 删除数据:像这样从RecyclerView适配器类中删除项目有四个步骤:

       list.remove(position);
       recycler.removeViewAt(position);
       adapter.notifyItemRemoved(position);                 
       mAdapter.notifyItemRangeChanged(position, list.size());
    

确保在您通知数据之后在这样的适配器类中设置数据

    private void setAdapter() {

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recycler_view.setLayoutManager(mLayoutManager);
    mAdapter = new BankDetailsAdapter(getBankList,this);
    recycler_view.setAdapter(mAdapter);
      }
  • 更新数据:有如下步骤来更新数据:

    adapter.notifyDataSetChanged();
    

它可以帮助您