Флажок не выдерживает изменения поворота экрана - PullRequest
0 голосов
/ 13 октября 2019

У меня есть приложение, которое я делаю для отработки MVVM. Это приложение просто вызывает Retrofit и рисует данные JSON в RecyclerView. В строке RecyclerView у меня есть флажок, функциональность которого заключается в том, что, если он отмечен, нажатие кнопки или показывает те отмеченные элементы в другом RecyclerView другого фрагмента. Проблема в том, что, когда я отмечаю чек, перед его отправкой или чем-либо, если я переворачиваю экран, происходит перезагрузка списка, или я не очень хорошо знаю, что делает поведение, но дело в том, что этот флажок снова не отмечени я хочу, чтобы, хотя я еще не отправил эти изменения в Retrofit, этот флажок остается:

Это мой класс просмотра:

package com.example.menunavegacion.ui.fragments.tabs.fragmentpets.view;


....

public class FragmentPets extends Fragment {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;

    PetsViewModel mWordViewModel;
    PetsAdapter adapter;

    @Inject
    RequestInterface requestInterface;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_tab_one, container, false);
        ButterKnife.bind(this, v);
        initViews();
        return v;
    }

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

        mWordViewModel = ViewModelProviders.of(this).get(PetsViewModel.class);

        mWordViewModel.getAllPets().observe(this, new Observer<ArrayList<PetsDTO>>() {
            @Override
            public void onChanged(ArrayList<PetsDTO> petsDTOS) {
                adapter = new PetsAdapter(petsDTOS, getContext(), false);
                recyclerView.setAdapter(adapter);
            }
        });

        mWordViewModel.getLoadingLiveData().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean loading) {
                if (loading) {
                    progressBar.setVisibility(View.VISIBLE);
                } else {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

        mWordViewModel.loadJSON();

        mWordViewModel.showFinishMessage().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    Toast.makeText(getActivity(), getActivity().getString(R.string.update_toast_message), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), getActivity().getString(R.string.message_send_error), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @OnClick(R.id.btnSend)
    public void onSend() {
        mWordViewModel.updateList(adapter.getPetList());
    }

    private void initViews() {
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
    }
}

Это моя модель представления:

package com.example.menunavegacion.ui.fragments.tabs.fragmentpets.viewmodel;

....

public class PetsViewModel extends AndroidViewModel implements ViewModelInterface.ViewModel {

    private PetsRepository mPetsRepository;
    private LiveData<ArrayList<PetsDTO>> mAllPets;

    public PetsViewModel (Application application){
        super(application);
        mPetsRepository = new PetsRepository(application);
        mAllPets = mPetsRepository.getAllPetsLiveData();
    }

    public LiveData<ArrayList<PetsDTO>> getAllPets() {
        return mPetsRepository.getAllPetsLiveData();
    }

    public LiveData<Boolean> getLoadingLiveData() {
        return mPetsRepository.getLoadingLiveData();
    }

    public LiveData<Boolean> showFinishMessage() {
        return mPetsRepository.getFinishMessage();
    }


    @Override
    public void loadJSON() {
        mPetsRepository.useCaseLoadJSON();
    }

    @Override
    public void updateList(ArrayList<PetsDTO> pets) {
        mPetsRepository.useCaseUpdateList(pets);
    }
}

Это хранилище:

package com.example.menunavegacion.ui.fragments.tabs;

....

public class PetsRepository {

    LoadJSONUseCase loadJSONUseCase;
    UpdateListUseCase updateListUseCase;

    private MutableLiveData<ArrayList<PetsDTO>> allPetsLiveData = new MutableLiveData<>();
    private MutableLiveData<Boolean> loadingLiveData = new MutableLiveData<>();
    private MutableLiveData<Boolean> showFinishMessage = new MutableLiveData<>();

    public LiveData<ArrayList<PetsDTO>> getAllPetsLiveData() {
        return allPetsLiveData;
    }
    public LiveData<Boolean> getLoadingLiveData() {
        return loadingLiveData;
    }
    public LiveData<Boolean> getFinishMessage() {
        return showFinishMessage;
    }

    public PetsRepository(Application application) {
        loadJSONUseCase = new LoadJSONUseCase();
        updateListUseCase = new UpdateListUseCase();
    }

    public void useCaseLoadJSON() {
        loadJSONUseCase.loadJSON(new RepositoryInterface() {
            @Override
            public void showError(Boolean show) {
                showFinishMessage.postValue(show);
            }

            @Override
            public void onLoading(boolean loading) {
                loadingLiveData.postValue(loading);
            }

            @Override
            public void onSuccess(ArrayList<PetsDTO> data) {
                allPetsLiveData.postValue(data);
            }
        });
    }

    public void useCaseUpdateList(ArrayList<PetsDTO> pets) {
        updateListUseCase.updateList(pets, new RepositoryInterface() {
            @Override
            public void showError(Boolean show) {
                showFinishMessage.postValue(show);
            }

            @Override
            public void onLoading(boolean loading) {
                loadingLiveData.postValue(loading);
            }

            @Override
            public void onSuccess(ArrayList<PetsDTO> data) {
                allPetsLiveData.postValue(pets);
            }
        });
    }

}

И это мой вариант использования. Прочитайте данные JSON с Retrofit:

package com.example.menunavegacion.ui.fragments.usecase;

....

public class LoadJSONUseCase {

    @Inject
    RequestInterface requestInterface;

    public LoadJSONUseCase(){
        DaggerComponenTest.builder().build().inject(this);
    }

    public void loadJSON(RepositoryInterface repositoryInterface) {
        Call<JSONResponse> call = requestInterface.getJSON();
        repositoryInterface.onLoading(true);
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
                repositoryInterface.onLoading(false);
                JSONResponse jsonResponse = response.body();
                ArrayList<PetsDTO> data = new ArrayList<>();
                data.clear();
                data.addAll(jsonResponse.getPetsDTO());
                repositoryInterface.onSuccess(data);
            }

            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
               repositoryInterface.onLoading(false);
               repositoryInterface.showError(false);
            }
        });

    }
}

Это был бы весь мой код. Я также принимаю советы по MVVM, так как я учусь, и, пожалуйста, я останусь с вами. Большое спасибо.

1 Ответ

0 голосов
/ 13 октября 2019

Речь идет о жизненном цикле и сохранении состояния вашего флажка. Так что эта ссылка поможет вам больше isaac Android CheckBox - Восстановление состояния после поворота экрана

...