我可以示例化datasource.factory,但是为什么不能在android中调用datasource.factory中的create()方法呢

0x6upsns  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(336)

我想显示一个api调用得到的房间列表。该应用程序使用android架构组件以及分页库。下面是我如何构建代码/应用程序的:
我有一个显示房间信息的片段。它观察viewmodel类中的数据,并在数据发生更改时更新
存储库通过api调用获取数据并将其作为列表返回
此时,我想将返回的房间列表转换为pagedlist,我可以将其传递回pageradapter,以便在ui上显示
为此,我有一个datasource.factory,它创建datasource并传递存储库返回的列表。此时datasource.factory不会调用create()方法,ui也不会更新。
代码如下:
碎片:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.rooms_fragment, container, false);

        swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        recyclerView = rootView.findViewById(R.id.recycler_view);

        //add empty view
        emptyRoomsList = rootView.findViewById(R.id.empty_list);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext().getApplicationContext());
        //layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        //intialise and set the adapter
        roomAdapter = new MyRoomCardRecyclerViewAdapter("My Rooms");
        recyclerView.setAdapter(roomAdapter);

        //connect the view model
        myRoomsSummaryViewModel = ViewModelProviders.of(this).get(RoomSummaryViewModel.class);
        setUpProgressDialog();
        //observe the data and update the viewmodel when changes occur in the data
        getAllCurrentUserRooms();

        //check if network is present,
        // ToDo:
        // run the query in the background

        //setup the swipeToRefreshLayout i.e. onSwipeDown, fetch new rooms added
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //invalidate datasorucefactory
                myRoomsSummaryViewModel.invalidateCurrentUserDatasource(ParseUser.getCurrentUser().getObjectId());
                getAllCurrentUserRooms();
            }
        });

        //configure the swipe refresh colours
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

        return rootView;
    }

    private void getAllCurrentUserRooms() {
        myRoomsSummaryViewModel.getmAllCurrentUserRooms(ParseUser.getCurrentUser().getObjectId()).observe(getViewLifecycleOwner(), new Observer<PagedList<RoomSummaryModel>>() {
            @Override
            public void onChanged(PagedList<RoomSummaryModel> parseObjects) {
                Log.i("My Rooms: ", "MyRoomsFrag: Room 1 " + parseObjects.size() + " " + parseObjects.get(0).getObjectId());
                roomAdapter.submitList(parseObjects);
                progressDialog.dismiss();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

视图模型

public class RoomSummaryViewModel extends AndroidViewModel {
...        
public LiveData<PagedList<RoomSummaryModel>> getmAllCurrentUserRooms(String currentUserID){
        Log.i("Logged Webservice: ", "Webservice observe " );
//        mAllCurrentUserRooms = roomSummaryRepository.getCurrentlyLoggedinUserRooms(currentUserID);
        mAllCurrentUserRooms = loggedinUserRoomsRepository.getLoggedInUserRooms();
//        Log.i("ViewModel Rooms: ", "ViewModel rooms: " + mAllCurrentUserRooms.getValue().get(0).getObjectId());
        return mAllCurrentUserRooms;
    }
...
}

存储库和3。转换为页面列表:

public class LoggedinUserRoomsRepository {
public LoggedinUserRoomsRepository(){
        RetrofitClientInstance retrofitClientInstance = new RetrofitClientInstance();
        loggedInUserRoomsWebService = retrofitClientInstance.getRetrofitInstance()
                .create(LoggedInUserRoomsWebService.class);
        Log.i("LoggedinRepo: ", "LoggedinUser repository constructor");
    }
    //create a handle for the Retrofit interface
    private LoggedInUserRoomsWebService loggedInUserRoomsWebService;

    private LiveData<PagedList<RoomSummaryModel>> currentUserRooms = new MutableLiveData<>();

    LoggedinUserDataSourceFactory loggedinUserRoomsDataSource;

    /*
    * Return the list of rooms
    * Use the returned list in a datasource
    * */
    public LiveData<PagedList<RoomSummaryModel>> getLoggedInUserRooms(){
        //paged list builder
        PagedList.Config pagegListConfig = new PagedList.Config.Builder().setEnablePlaceholders(false)
                .setPrefetchDistance(6)
                .setInitialLoadSizeHint(12)
                .setPageSize(8).build();

        Log.i("Web service:", "Web service in repository");
        Call<RoomsResponseModel> call = loggedInUserRoomsWebService.getLoggedInUserRooms();
        call.enqueue(new Callback<RoomsResponseModel>() {
            @Override
            public void onResponse(Call<RoomsResponseModel> call, Response<RoomsResponseModel> response) {
                Log.i("Webservice response: ", "Webservice response: " + response.body().getRoomsReturned().size() + " " + response.raw());
                Log.i("Webservice response: ", "Webservice response: " + response.body().getRoomsReturned().get(0).getObjectId());
//                Gson gson = new GsonBuilder().create();
//                RoomsResponseModel roomsResponseModel = response.body();
//                RoomsResponseModel roomsResponse = new RoomsResponseModel();
                /*
                * 1. create the datasource
                * 2. pass the list to the datasource
                * */

                List<RoomSummaryModel> roomsReturned = new ArrayList<>();
                roomsReturned = response.body().getRoomsReturned();

                Log.i("Rooms returned: ", "Rooms list " + roomsReturned.get(0).getObjectId() + " " + roomsReturned.size());

                PagedList.Config pagegListConfig = new PagedList.Config.Builder().setEnablePlaceholders(false)
                        .setPrefetchDistance(6)
                        .setInitialLoadSizeHint(12)
                        .setPageSize(8).build();

                loggedinUserRoomsDataSource = new LoggedinUserDataSourceFactory(roomsReturned);

                currentUserRooms = new LivePagedListBuilder(loggedinUserRoomsDataSource, pagegListConfig).build();

//                getAllRooms();

//                roomsResponse = response.body();
//                Log.i("Rooms returned: ", "Webservice rooms returned " + currentUserRooms.getValue().get(0).getObjectId());
            }

            @Override
            public void onFailure(Call<RoomsResponseModel> call, Throwable t) {
                Log.e("Error", "Error retrieving rooms from webservice; " + t.getMessage());
                //ToDo
                /*
                * Dismiss the loader
                * Retry
                * */

            }
        });

//        Log.i("Rooms returned: ", "Current rooms pagedlist returned: " + currentUserRooms.getValue().get(0).getObjectId());
        return currentUserRooms;
    }
...
}

datasource.factory(此处不调用create()方法)和datasource:

public class LoggedinUserDataSourceFactory extends DataSource.Factory<String, RoomSummaryModel> {
    public LoggedinUserDataSourceFactory(List<RoomSummaryModel> roomsReturned) {
        Log.i("Factory constructor:", "Logged in user factory constructor: " + roomsReturned.get(0).getObjectId());
        this.roomSummaryModels = roomsReturned;
//        create();
    }

    List<RoomSummaryModel> roomSummaryModels;

    @NonNull
    @Override
    public DataSource<String, RoomSummaryModel> create() {
        Log.i("Factory:", "Logged in user factory 'create()': ");
        LoggedinUserRoomsDataSource loggedinUserRoomsDataSource = new LoggedinUserRoomsDataSource(roomSummaryModels);
//        LoggedinUserDataSourceFactory loggedinUserDataSourceFactory = new LoggedinUserDataSourceFactory(roomSummaryModels);
        Log.i("Logged in DS: ", "Logged in DS: " + roomSummaryModels.get(0).getObjectId());
        return loggedinUserRoomsDataSource;
    }
}

数据源:

public class LoggedinUserRoomsDataSource extends ItemKeyedDataSource<String, RoomSummaryModel> {

    public LoggedinUserRoomsDataSource(){}

    public LoggedinUserRoomsDataSource(List<RoomSummaryModel> roomsResponseModel){
        this.roomsResponseModels = roomsResponseModel;
        Log.i("Rooms Datasource: ", "Rooms in datasource: " + roomsResponseModels.size() + " " + roomsResponseModels.get(0).getObjectId());
//        loadInitial();
    }

    List<RoomSummaryModel> roomsResponseModels;

    @Override
    public void loadInitial(@NonNull LoadInitialParams<String> params, @NonNull LoadInitialCallback<RoomSummaryModel> callback) {
        //get logged in user rooms
//        LoggedinUserRoomsRepository loggedinUserRoomsRepository = new LoggedinUserRoomsRepository();
//
        Log.i("Rooms Datasource: ", "Load initial Rooms in datasource: " + roomsResponseModels.size() + " " + roomsResponseModels.get(0).getObjectId());
        callback.onResult(roomsResponseModels, 0, roomsResponseModels.size() );
    }

    @Override
    public void loadAfter(@NonNull LoadParams<String> params, @NonNull LoadCallback<RoomSummaryModel> callback) {
        //get additional rooms from logged in user
    }

    @Override
    public void loadBefore(@NonNull LoadParams<String> params, @NonNull LoadCallback<RoomSummaryModel> callback) {

    }

    @NonNull
    @Override
    public String getKey(@NonNull RoomSummaryModel item) {
        return null;
    }
}

任何关于我做得不对的建议都将不胜感激。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题