【问题标题】:View model not returning any data after reloading fragment重新加载片段后视图模型不返回任何数据
【发布时间】:2020-05-31 01:49:12
【问题描述】:

尝试实施:

1.从视图模型加载数据之前的互联网检查。 2.片段不应该从视图模型中获取任何数据(不设置任何观察者),如果它们没有连接,则显示警报对话框。 3.如果连接可用,则使用警报对话框中的“重试”按钮从视图模型重新加载/获取数据。

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

我还尝试重新加载整个片段,而不仅仅是使用以下代码调用“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;
    }
}

当互联网连接发生时,我的片段如下所示:

再次按下尝试后,方法(getDataFromViewModel)被调用,但视图模型没有返回任何数据。但是当我从一开始加载具有互联网的片段时,相同的方法工作正常。是否因为我初始化的方式而发生并在视图模型或其他东西上设置观察者?请帮助并建议我如何解决这个问题。

【问题讨论】:

    标签: android-studio android-fragments android-livedata android-viewmodel


    【解决方案1】:

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

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

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

    你可以做些什么来解决它:

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

    这样,只有当你观察到这个 globalData

    时,你才会触发网络获取

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

    【讨论】:

    • 谢谢你的兄弟。你说得对导致这个问题的原因是正确的。正如你所说,我将这部分 globalData = repository.getGlobalData(); 删除到另一种方法:public void init() { if (globalData==null) globalData = repository.getGlobalData(); }。仅当他们的互联网连接正常时才调用该方法,以确保我没有尝试在没有互联网的情况下触发网络获取,正如您所指出的那样。现在它工作得很好。再次感谢
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2019-06-27
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多