1

我正在尝试构建一个应用程序来从服务器获取提要列表并在 Recyclerview 中显示。我正在尝试这样的 LiveData 基本实现。

我在我的片段中设置了一个观察者,如下所示:

viewModel = ViewModelProviders.of(getActivity()).get(SellViewModel.class);

    viewModel.getSellItemList(19).observe(this, new Observer<List<LambdaSellRequestClass>>() {
            @Override
            public void onChanged(@Nullable List<LambdaSellRequestClass> sellItems) {


                adapter.setSellEntities(sellItems);

            }
        });

我的 SellViewModel 类是这样的:

public class SellViewModel extends AndroidViewModel {

private SellRepository repository;

private MutableLiveData<List<LambdaSellRequestClass>> sellItems;

public SellViewModel(@NonNull Application application) {
    super(application);
    repository = new SellRepository(application);

    try {
        if (sellItems == null) {
            sellItems = new MutableLiveData<>();
            sellItems.postValue(repository.getSellItemList(user_id));
        }
    }catch (Exception e) {
        Log.d("SELLFRAGMENT", "Error: " + e.getLocalizedMessage());
    }
}

public MutableLiveData<List<LambdaSellRequestClass>> getSellItemList(int userId) throws ExecutionException, InterruptedException {

    return sellItems;
}

}

我的 SellRepository 是这样的:

public class SellRepository {

public SellRepository(Application application) {

}

    public List<LambdaSellRequestClass> getSellItemList(int userId) throws ExecutionException, InterruptedException {

        return new SellRepository.GetSellItemListAsync(SellRepository.this).execute(userId).get();

    }

   private static class GetSellItemListAsync extends AsyncTask<Integer, Void, List<LambdaSellRequestClass>> {

        List<LambdaSellRequestClass> list = new ArrayList<>();      

        public GetSellItemListAsync() {

        }

        @Override
        protected List<LambdaSellRequestClass> doInBackground(Integer... integers) {

            final int userID = integers[0];


          list =     

     lambdaFunctionsCalls.getSellItemByUser_lambda(requestClass).getSellItems();

            return list;
        }
  }

我的问题是当我将新的销售商品添加到数据库时,它不会更新移动应用程序。

4

0 回答 0