Как загрузить больше данных сверху вниз с помощью recyclerview в android? - PullRequest
1 голос
/ 06 августа 2020

Я пытаюсь загрузить больше данных при прокрутке сверху вниз в android. Я использую абстрактный метод loadmoreItems(). Я загружаю данные из laravel api для отображения в recyclerview и загружаю больше данных при прокрутке вверху. когда я загружаю больше данных, приложение показывает неверные данные.

LinearLayoutManager layoutManager;
String scroll_type="bottom_top";
public PaginationScrollListener(LinearLayoutManager layoutManager) {
    this.layoutManager = layoutManager;
}
public PaginationScrollListener(LinearLayoutManager layoutManager,String scroll_type) {
    this.layoutManager = layoutManager;
    this.scroll_type = scroll_type;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);
        int visibleItemCount = layoutManager.getChildCount();
        int totalItemCount = layoutManager.getItemCount();
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
        if (!isLoading() && !isLastPage()) {
        if(scroll_type.equalsIgnoreCase("top_bottom")){
            if (firstVisibleItemPosition == 0) {
                loadMoreItems();
            }
        }else {
            if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                    && firstVisibleItemPosition >= 0) {
                loadMoreItems();
            }
        }
    }

}

protected abstract void loadMoreItems();

/*public abstract int getTotalPageCount();*/

public abstract boolean isLastPage();

public abstract boolean isLoading();

Это активность в чате. Я хочу получить данные чата с сервера и показать их в чате. Я пытаюсь получить данные с помощью разбивки на страницы и хочу загрузить больше данных при прокрутке сверху вниз.

public class Chatactivity extends AppCompatActivity implements Consumes {
    @Inject
    ViewModelFactorys viewModelFactorys;
    Chatviewmodel chatviewmodel;
    Button send;
    TextView message;
    TextView department;
    TextView name;
    private int page = 1;
    static RecyclerView rv_chat;
    private ChatAdapter chatadapter;
    private boolean is_item_cleared = true;
    private boolean isLastPage = false;
    private boolean isLoading = false;
    private Loginmodel loginmodel;
    LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        loginmodel = new Gson().fromJson(SharedPref.Getloggeduserdetials(SharedPref.LOGGOEDUSERDATABASE, ""), Loginmodel.class);

        send = findViewById(R.id.send);
        message = findViewById(R.id.message);
        rv_chat = findViewById(R.id.rv_chat);
        department = findViewById(R.id.department);
        name = findViewById(R.id.name);

        ((Myapp) getApplication()).getAppComponent().doInjection(Chatactivity.this);
        chatviewmodel = ViewModelProviders.of(this, viewModelFactorys).get(Chatviewmodel.class);
        chatviewmodel.apiResponse().observe(this, this::consumeResponsess);

        linearLayoutManager = new LinearLayoutManager(this);
        //linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_chat.setLayoutManager(linearLayoutManager);
        chatadapter = new ChatAdapter(this, Chatactivity.this);
        rv_chat.setAdapter(chatadapter);
        name.setText(loginmodel.getName());
        department.setText(loginmodel.getDepartment());
        chatviewmodel.receive_msg(String.valueOf(page), SharedPref.getToken(SharedPref.TOKEN, ""), Chatactivity.this);
        send.setOnClickListener(view ->
        {
            chatviewmodel.send_msg(message.getText().toString(), SharedPref.getToken(SharedPref.TOKEN, ""), Chatactivity.this);
            message.setText("");
        });


        rv_chat.addOnScrollListener(new PaginationScrollListener(linearLayoutManager,"top_bottom") {

            @Override
            protected void loadMoreItems() {
                isLoading = true;
                if (!isLastPage) {
                    Log.d("Scroll","last page");
                    //if (!rv_chat.canScrollVertically(-1)) {
                    Log.d("Scroll","canScrollVertically");
                    //if (linearLayoutManager.findFirstVisibleItemPosition() == 0 && listIsAtTop()) {
                    Log.d("Scroll","find item position");
                    new Handler().postDelayed(() -> {
                        is_item_cleared = false;
                        chatviewmodel.receive_msg(String.valueOf(page), SharedPref.getToken(SharedPref.TOKEN, ""), Chatactivity.this);
                    }, 200);
                    //}
                    //}
                }
            }

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

            @Override
            public boolean isLoading() {
                return isLoading;
            }
        });
    }
    private boolean listIsAtTop() {
        if (rv_chat.getChildCount() == 0) return true;
        return rv_chat.getChildAt(0).getTop() == 0;
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(this, Profile_Activity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    @Override
    public void handleresponse(ApiResponse apiResponse) {
        Pagination<ChatModel> pagination = (Pagination<ChatModel>) apiResponse.data.getData();
        Log.w("Api Response", new GsonBuilder().setPrettyPrinting().create().toJson(apiResponse.data.getData()));
        isLoading = false;
        isLastPage = false;
        if (apiResponse.data.getSuccess().equalsIgnoreCase("1")) {
            if (apiResponse.data.getData() instanceof Pagination) {
                if (apiResponse.data.getData() != null) {
                    if (pagination.getData() != null) {
                        if (chatadapter != null) {
                            if (is_item_cleared) {
                                chatadapter.clearitem();
                            }
                            int last_position=linearLayoutManager.findLastVisibleItemPosition();
                            chatadapter.addItems(pagination.getData());
                            if (is_item_cleared) {
                                rv_chat.scrollToPosition(chatadapter.getItemCount() - 1);
                            }else{
                                List<ChatModel> pageChats=pagination.getData();
                                int visibleItemCount = linearLayoutManager.findLastVisibleItemPosition() - linearLayoutManager.findFirstVisibleItemPosition();
                                rv_chat.scrollToPosition(last_position);
                            }

                            if (pagination.getNextPageUrl() == null)
                                isLastPage = true;
                            else
                                page += 1;
                        }
                    }
                }
            } else {
                page = 1;
                is_item_cleared = true;
                chatviewmodel.receive_msg(String.valueOf(page), SharedPref.getToken(SharedPref.TOKEN, ""), Chatactivity.this);
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...