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

Asked

Viewed 215 times

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 populated in Textviews is removed.

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

  • https://developer.android.com/topic/libraries/architecture/guide.html

  • Thank you very much, @ramaral...exactly what I wanted. Problem solved.

1 answer

0

To 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 the 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 recommend using Rxandroid and Rxlifecycle to control the life cycle

  • Thanks @Duanniston, I used exactly these methods and it worked. As for the recommendations, thank you and I will study them. I had already recommended the Retrofit, I just used Asynctask for knowledge and study.

Browser other questions tagged

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