简体   繁体   English

如何在Recyclerview中更新数据?

[英]How Can I Update data in Recyclerview?

I Build an app that load data with Retrofit , into a recyclerview, my recyclerview load perfectly all data from JSON file, but when I try of an update with swipeRefreshLayout , and I intent load again the method loadFirstPage(); 我构建了一个使用Retrofit将数据加载到recyclerview的应用程序,我的recyclerview完美地从JSON文件加载了所有数据,但是当我尝试使用swipeRefreshLayout更新时,我又打算再次加载方法loadFirstPage(); , but simply add again the same data. ,但只需再次添加相同的数据即可。

I search in google for any solution, but all my intents do not work in my code. 我在google中搜索任何解决方案,但我的所有意图均不适用于我的代码。

I intent used adapter.clear and load again, but not work fine. 我打算使用adapter.clear并再次加载,但不能正常工作。

The idea is if 1 item change from JSON file, update again the data in Recyclerview. 这个想法是,如果从JSON文件更改了1个项目,请再次更新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() {

    }
}

Try this: 尝试这个:

it is very simple to update and remove data in recycler view 在回收者视图中更新和删除数据非常简单

  • REMOVE Data : There are 4 steps to remove an item from a RecyclerView adapter class like this: 删除数据:共有4个步骤,从RecyclerView适配器类中删除一个项目,如下所示:

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

make sure your data is set in adapter class like this after that you notifyData 在您通知数据之后,确保像这样在适配器类中设置数据

    private void setAdapter() {

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recycler_view.setLayoutManager(mLayoutManager);
    mAdapter = new BankDetailsAdapter(getBankList,this);
    recycler_view.setAdapter(mAdapter);
      }
  • UPDATE data : There are 1 steps to update data like this: UPDATE data :有如下步骤来更新数据:

     adapter.notifyDataSetChanged(); 

it helps you 它可以帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM