How can I "keep" an Activity data when I rotate the screen?

0

I have an Activity that makes an HTTP request using AsyncTask, the result of this request is sent to a method that updates my UI. But when I rotate the screen, the data entered in TextViews is removed.

How can I "keep" this data when I rotate the screen?

    
asked by anonymous 23.05.2017 / 17:33

1 answer

0

For activity's

To save the data

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Salve todos seus dados aqui, lembrando que se for objeto é preciso ser serializable ou de preferencia parcelable
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Sempre chamar a super classe depois de salvar as instancias
    super.onSaveInstanceState(savedInstanceState);
}

To recover data

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); //Sempre chamar a super classe primeiro

    // Verifique se existe algo para restaurar
    if (savedInstanceState != null) {
        // Restaurando os valores padrão
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Não existe valores para restaurar
    }
    ...
}

More details on this link

I recommend not using AsyncTask and yes Retrofit for HTTP and for threads I recommend using RxAndroid and RxLifecycle to control the life cycle

    
23.05.2017 / 19:42