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

问题描述 投票:0回答:1

试图实现

1.在从视图模型中加载数据前进行网络检查。2.片段不应该从视图模型中获取任何数据(不设置任何观察者),如果没有连接,则显示警报对话框。

问题:当我试图通过 "再试一次 "按钮重新加载数据时,没有从视图模型中获取数据。如果我从一开始就有网络连接,那么就不会发生这种情况,视图模型可以正常工作。但如果我从一开始就没有网络连接,并尝试从 "再试一次 "按钮重新加载数据,那么就会发生。

我也试过用下面的代码重新加载整个片段,而不是只调用 "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();
        }

但这也不行。

这是我的片段类。

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();

    }
}

我的视图模型类:

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;
    }
}

当网络连接发生时,我的片段看起来是这样的。Alert Dialog

After press try again the method(getDataFromViewModel) is called but view model is not returning any data.But the same method is working fine when I load the fragment having internet from the beginning.Is it happening because the way I initialize and set observer on view model or something else?Please help and suggest me how to solve this problem.

android-studio android-fragments android-livedata android-viewmodel
1个回答
1
投票

你没有显示你的仓库配置,无论如何,我相信你的问题是你在没有互联网的情况下从你的仓库(在这种情况下,我相信是在外部网络[互联网])中获取数据,你没有试图再次获取,总之,你观察到了这一点。

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

由于你在初始化viewmodel的时候没有网络连接,所以它是空的。

你可以做什么来解决它。

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

这样一来,只有当你观察到这样的情况时,你才会触发网络取数。全局数据

让我知道,如果它对你有意义。

© www.soinside.com 2019 - 2024. All rights reserved.