重新加载片段后视图模型不返回任何数据

View model not returning any data after reloading fragment

正在尝试实施:

1.An 在从视图模型加载数据之前检查互联网。 2.The 片段不应该从视图模型中获取任何数据(不设置任何观察者),如果它们没有连接则显示警告对话框。 3.If 连接可用 reload/fetch 使用警报对话框内的 "try again" 按钮来自视图模型的数据。

问题: 但是当尝试从重试按钮重新加载数据时,没有从视图模型中获取数据。如果我从一开始就有互联网连接就不会发生,然后视图模型就可以正常工作。但是,如果我从一开始就没有互联网并尝试从 "try again" 按钮重新加载数据,那么就会发生。

我还尝试重新加载整个片段,而不是仅使用以下代码调用 "getDataFromViewModel" 方法:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getParentFragmentManager().beginTransaction().detach(this).commitNow();
            getParentFragmentManager().beginTransaction().attach(this).commitNow();
        } else {
            getParentFragmentManager().beginTransaction().detach(this).attach(this).commit();
        }

但这也行不通。

这是我的片段class:

public class GlobalDataFragment extends Fragment implements AlertDialogClass.AlertDialogClickInterface {


    public GlobalDataFragment() {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication())).get(GlobalDataViewModel.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_global_data, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        totalCase = (TextView) view.findViewById(R.id.tvTotalCases);
        activeCase = (TextView) view.findViewById(R.id.tvActiveCases);
        recovered = (TextView) view.findViewById(R.id.tvRecovered);
        caseToday = (TextView) view.findViewById(R.id.tvTodayCase);
        casePM = (TextView) view.findViewById(R.id.tvCasesPM);
        todayDeath = (TextView) view.findViewById(R.id.tvTodayDeaths);
        totalDeath = (TextView) view.findViewById(R.id.tvTotalDeaths);
        deathsPM = (TextView) view.findViewById(R.id.tvDeathsPM);
        criticalCondition = (TextView) view.findViewById(R.id.tvCriticalCase);
        totalTested = (TextView) view.findViewById(R.id.tvTested);
        testsPM = (TextView) view.findViewById(R.id.tvTestsPM);
        affectedCountries = (TextView) view.findViewById(R.id.tvAffectedCountries);
        simpleArcLoader = (ProgressBar) view.findViewById(R.id.simpleArcLoader);
        pieChart = (PieChart) view.findViewById(R.id.pieChart);
        nestedScrollView = (ScrollView) view.findViewById(R.id.nestedScrollView);
        navController = Navigation.findNavController(view);
        alertDialogClass = new AlertDialogClass(getContext(), this);


        getDataFromViewModel();


    }

    private void getDataFromViewModel() {
        try {
            if (CheckConnection.isConnected()) {

                viewModel.getGlobalData().observe(getViewLifecycleOwner(), this::setViewData);

            } else {

                alertDialogClass.show();

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void setViewData(GlobalData globalData) {

        if (globalData != null) {
            totalTested.setText(globalData.getTests());
            testsPM.setText(globalData.getTestsPerOneMillion());
            affectedCountries.setText(globalData.getAffectedCountries());


            setPieGraph(globalData);
            simpleArcLoader.setVisibility(View.GONE);
            nestedScrollView.setVisibility(View.VISIBLE);


        }
    }

//Called when clicked on try again button of alert dialog
    @Override
    public void OnAlertButtonClicked() {

        alertDialogClass.dismiss();
        getDataFromViewModel();

    }
}

我的视图模型Class:

public class GlobalDataViewModel extends AndroidViewModel {

    private Repository repository;
    private LiveData<GlobalData> globalData = new MutableLiveData<>();

    public GlobalDataViewModel(@NonNull Application application) {
        super(application);

        repository = Repository.getInstance();
        globalData = repository.getGlobalData();

    }


    public void init() {

    }

    public LiveData<GlobalData> getGlobalData() {
        return globalData;
    }
}

当出现 Internet 连接时,我的片段看起来像这样:

按下重试后调用方法 (getDataFromViewModel) 但视图模型未返回任何 data.But 当我从 beginning.Is 加载具有互联网的片段时,相同的方法工作正常因为我在视图模型或其他东西上初始化和设置观察者的方式?请帮助并建议我如何解决这个问题。

你没有显示你的存储库配置,无论如何我认为你的问题是你在没有互联网的情况下从你的存储库中获取数据(在这种情况下我认为是在外部网络 [internet] 中)并且你没有尝试再次获取,总结一下,你正在观察这个:

private LiveData<GlobalData> globalData = new MutableLiveData<>();

并且由于您在初始化视图模型时没有互联网连接,所以它是空的。

您可以采取什么措施来修复它:

private LiveData<GlobalData> globalData = repository.getGlobalData();

这样,你只会触发网络获取 if/when 你观察到这个 globalData

让我知道它是否对你有意义。