Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

android - cannot create an instance of class viewmodel with viewpager and tablayout

I am implementing MVVM and using viewpager2 with tablayout attached on a fragment
I have a viewmodel class for each fragment of the tablayout, I am getting this runtime error
"cannot create an instance of class viewmodel with viewpager'

Here is my viewmodel classes:

public class CranesViewModel extends AndroidViewModel {
    private IndustrialCranesRepository repository;
    private LiveData<List<TrackingModel>> allIndustrialTrackingItems;


    public CranesViewModel(@NonNull Application application) {
        super(application);
        repository = new IndustrialCranesRepository(application);
        allIndustrialTrackingItems = repository.getAllIndustrialData();

    }

    public LiveData<List<TrackingModel>> getAllIndustrialTrackingItems() {
        return allIndustrialTrackingItems;
    }
public class ConstructionViewModel extends AndroidViewModel {

    private ConstructionPortMaritimeRepository repository;
    private LiveData<List<ConstructionModel>> allConstructionTrackingItems;


    public ConstructionViewModel(@NonNull Application application) {
        super(application);
        repository = new ConstructionPortMaritimeRepository(application);

        allConstructionTrackingItems = repository.getAllConstructionData();
    }

    public LiveData<List<ConstructionModel>> getAllConstructionTrackingItems()
    {
        return allConstructionTrackingItems;
    }

}

Fragment code:

  @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(requireActivity()).get(ConstructionViewModel.class);

        viewModel.getAllConstructionTrackingItems().observe(requireActivity(), new Observer<List<ConstructionModel>>() {
            @Override
            public void onChanged(List<ConstructionModel> constructionModels) {
                ConstructionAdapter adapter = new ConstructionAdapter(constructionModels, ConstructionFragment.this);
                constructionRecyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        });

Why am I getting this error?

question from:https://stackoverflow.com/questions/65910623/cannot-create-an-instance-of-class-viewmodel-with-viewpager-and-tablayout

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...