Spinner behavior with database data in Lifecycle

Asked

Viewed 99 times

0

I have 3 Spinners inside a Fragment, the problem I’m having is when I rotate the Tablet screen and the screen rebuilds, so the Spinners are zeroed.

The first Spinner comes from the bank, depending on the selection of the first Spinner the second is filled and so does the third Spinner when I choose the second.

I already handle the data, because when selecting the item it already saved in the database, however, when rotating the screen I have the problems described above, follows a method that I use to show the saved item even leaving the screen...

public void setSpinnerSelection(Spinner spinner, Adapter adapter, String text) {
    for (int i = 0; i < adapter.getCount(); i++) {
        String comparar = adapter.getItem(i).toString();
        if (comparar.equals(text)) {
            spinner.setSelection(i);
        }
    }
}

I noticed something strange too, is it common when Fragment is rebuilt it performs what is inside that Spinner method? " setOnItemSelectedListener", I realized that this is exactly the "bottleneck".

In short, I wanted to know an intelligent way to work with the life cycle of Fragment.

2 answers

1

You must do the override of the method onSaveInstanceState and save the indexes of the selected items of each spinner.
Later, when the Fragment is recreated, you can obtain these values through the Bundle passed to the method onActivityCreated.

It’ll be something like:

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    bundle.putLong("indice1", spinner1.getSelectedItemPosition());
    bundle.putLong("indice2", spinner2.getSelectedItemPosition());
    bundle.putLong("indice3", spinner3.getSelectedItemPosition());

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        //Restore the fragment's state
        int index1 = savedInstanceState.getLong("indice1");
        int index2 = savedInstanceState.getLong("indice2");
        int index3 = savedInstanceState.getLong("indice3");

    }
}

0


I figured out how to solve this problem...

Just use the Spinner setOnTouchListener...

    spinner.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // Marca como selecionado.
            chave = true;
            return false;
        }
    });

Once you make the key TRUE, just use it like this...

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (chave) {
            //Instrução...

            }
    }

Thus, even if Fragment or Activity reconstructs, the values remain...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.