Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 由于ViewModel中的项目计数错误,无法滚动RecyclerView_Android_Retrofit_Android Mvvm - Fatal编程技术网

Android 由于ViewModel中的项目计数错误,无法滚动RecyclerView

Android 由于ViewModel中的项目计数错误,无法滚动RecyclerView,android,retrofit,android-mvvm,Android,Retrofit,Android Mvvm,我正在开发一个用于搜索github用户的简单应用程序(利用)。不幸的是,返回多个项目的请求在默认情况下将分页为30个项目。因此,您必须使用自己的分页机制 这是我的简单逻辑: TOTAL_PAGES = ceil(total_count/30) if (currentPage < TOTAL_PAGES) { currentPage++; doSearchUser(who, currentPage); } 它产生的总页数为33,这意味着我们的总页数为2 以及一些有关守则:

我正在开发一个用于搜索github用户的简单应用程序(利用)。不幸的是,返回多个项目的请求在默认情况下将分页为30个项目。因此,您必须使用自己的分页机制

这是我的简单逻辑:

TOTAL_PAGES = ceil(total_count/30)

if (currentPage < TOTAL_PAGES) {
    currentPage++;
    doSearchUser(who, currentPage);
}
它产生的总页数为33,这意味着我们的总页数为2

以及一些有关守则:

MainActivity.java

 private void doSearchUser(String who, int pageNum) {
    totalCount = viewModel.getTotalCount();
    viewModel.setSearchResult(who, pageNum);

    viewModel.getSearchResult().observe(this, new Observer<ArrayList<User>>() {
        @Override
        public void onChanged(ArrayList<User> theList) {
            searchAdapter = new SearchAdapter(context, theList);
            recyclerView.setAdapter(searchAdapter);
        }
    });

    totalCount = viewModel.getTotalCount(); // not working. always returns 0 :(
    TOTAL_PAGES = ((int)Math.ceil((double) totalCount/(double)30));
}

    private void setUpRecyclerView() {
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        List<User> userList = new ArrayList<User>();
        searchAdapter = new SearchAdapter(context, userList) ;

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(searchAdapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                if(!recyclerView.canScrollVertically(1) && dy != 0) {
                    if (currentPage < TOTAL_PAGES) {
                        currentPage++;
                        doSearchUser(who, currentPage);
                    }
                }
            }
        });
    }
package com.divbyzero.app.githubusersearch.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.divbyzero.app.githubusersearch.api.APIEndPoint;
import com.divbyzero.app.githubusersearch.api.APIService;
import com.divbyzero.app.githubusersearch.response.SearchResponse;
import com.divbyzero.app.githubusersearch.model.User;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class UserViewModel extends ViewModel {

    private MutableLiveData<ArrayList<User>> mutableLiveData = new MutableLiveData<>();
    private int totalCount;
    private ArrayList<User> savedData = new ArrayList<User>();

    public void setSearchResult(String who, int page){
        Retrofit retrofit = APIService.getRetrofitService();
        APIEndPoint apiEndpoint = retrofit.create(APIEndPoint.class);
        Call<SearchResponse> call = apiEndpoint.getSearchResult(who, page);
        call.enqueue(new Callback<SearchResponse>() {
            @Override
            public void onResponse(Call<SearchResponse> call, Response<SearchResponse> response) {
                if (response.body() != null) {
                        savedData.addAll(response.body().getItems());
                        //mutableLiveData.setValue((ArrayList<User>) response.body().getItems());
                        mutableLiveData.setValue(savedData);
                        totalCount = response.body().getTotalCount();
                        Log.d("DBG", "OK");
                }
            }

            @Override
            public void onFailure(Call<SearchResponse> call, Throwable t) {
                Log.d("DBG", "Failed: "+t.getMessage());
            }
        });
    }

    public LiveData<ArrayList<User>> getSearchResult(){
        return mutableLiveData;
    }

    public void clear(){
        savedData.clear();
        mutableLiveData.setValue(new ArrayList<User>());
    }

    public int getTotalCount(){
        return totalCount;
    }
}
private void doSearchUser(字符串who,int pageNum){
totalCount=viewModel.getTotalCount();
viewModel.setSearchResult(who,pageNum);
viewModel.getSearchResult().observe(这是新的观察者


我的问题是
viewModel.getTotalCount()
最初返回0(而对于上面的URL,它应该返回33)。但这需要一段时间,最终它将返回33。这就是为什么我无法滚动查看更多项目的原因。如何解决此问题?

当您开始执行
viewModel.setSearchResult(who,pageNum)
这是异步api调用。您编写的代码不等待结果并继续,然后注册观察者。然后您尝试获取总计数,但api调用尚未完成。这就是为什么您得到0。您需要等待api调用何时完成。当您的livedata将有新项时,它将完成,对吗?这就是为什么在已更改
您将拥有totalCount=33

试着这样做

viewModel.getSearchResult().observe(this, new Observer<ArrayList<User>>() {
        @Override
        public void onChanged(ArrayList<User> theList) {
            totalCount = viewModel.getTotalCount();
            TOTAL_PAGES = ((int)Math.ceil((double) totalCount/(double)30));

            searchAdapter = new SearchAdapter(context, theList);
            recyclerView.setAdapter(searchAdapter);
        }
    });
viewModel.getSearchResult().observe(这是一个新的观察者(){
@凌驾
更改后的公共无效(ArrayList列表){
totalCount=viewModel.getTotalCount();
总页数=((int)Math.ceil((double)totalCount/(double)30));
searchAdapter=新的searchAdapter(上下文,列表);
recyclerView.setAdapter(searchAdapter);
}
});
viewModel.getSearchResult().observe(this, new Observer<ArrayList<User>>() {
        @Override
        public void onChanged(ArrayList<User> theList) {
            totalCount = viewModel.getTotalCount();
            TOTAL_PAGES = ((int)Math.ceil((double) totalCount/(double)30));

            searchAdapter = new SearchAdapter(context, theList);
            recyclerView.setAdapter(searchAdapter);
        }
    });