[FIXED] Saving progressbar progress when changing to landscape(Android,Java)

Issue

I am trying to save the progress of a progressbar when changing screen oriantation. I really dont know where to look for the answer and hope someone here could help me.

XML

        android:id="@+id/pb"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="90dp"
        android:layout_marginEnd="90dp"
        app:layout_constraintBottom_toTopOf="@+id/textViewBokstaver"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewTittel"
        app:layout_constraintVertical_bias="0.448" />```

Java
pb = (ProgressBar) findViewById(R.id.pb);
        pb.setVisibility(ProgressBar.VISIBLE);
        counter = 0;
        pb.setMax(15);

counter++;
pb.setProgress(counter);

I have button where everytime it get clicked on will increase the progress, but when i change the oriantation the progress resets.

Thanks in advance.

Solution

Save your progress value in onSaveInstanceState():

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("prog_key", counter);
}

Restore your value in onCreate():

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        counter = savedInstanceState.getInt("prog_key");
        pb.setProgress(counter); //ProgressBar must be initialized before this
    }
}

Answered By – Leonid

Answer Checked By – Candace Johnson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published