안드로이드 자바

[Java][Android] 화면이 회전 되었을 때 이전 액티비티의 데이터 유지하기

teamnova 2022. 8. 29. 12:00
728x90

안녕하세요

오늘은 안드로이드 디바이스를 회전 했을 때, 데이터를 유지하는 방법에 대해 알아보겠습니다.

먼저 영상부터 함께 보겠습니다.

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

영상과 같이 기본적으로 안드로이드에서 화면을 회전 시키면 기존 액티비티가 지워지고 새로 다시 만들어지게 되는데요.

이때 이전 액티비티에서 입력 받았던 데이터들이 전부 사라지게 됩니다.

 

하지만 이 데이터를 저장할 수 있는 방법이 있는데요.

바로 매개변수 saveInstanceState에 이전 액티비티의 데이터를 Bundle 형태로 저장 후, onCreate() 함수에서 로딩해주면 화면이 회전 되어도 데이터를 그대로 유지시킬 수 있습니다. (저장된 데이터를 다시 불러옴)

 

이제 예제 함께 보겠습니다.

 

먼저 xml 파일입니다.

<!--activity_rotation.xml-->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ActivityRotation"
    android:orientation="vertical"
    android:padding="4dp">

    <TextView
        android:id="@+id/level"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="레벨 : 0"/>

    <Button
        android:id="@+id/btn_levelup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="레벨 증가"
        android:onClick="onLevelUp"/>

    <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="점수 : 0"/>


    <Button
        android:id="@+id/btn_scoreup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="점수 증가"
        android:onClick="onScoreUp"/>

</LinearLayout>

이번 예제에서는 화면의 [레벨 증가] 버튼과 [점수 증가] 버튼을 클릭해서 각 레벨과 점수 값을 세팅해준 후에, 

화면을 회전 시키면 데이터가 유지되는 것을 해볼 예정입니다.

보시는 것과 같이 onClick으로 클릭 메서드를 정의하였습니다.

 

이제 자바 코드입니다.

// ActivityRotation.java

public class ActivityRotation extends AppCompatActivity {

    public static final String STATE_LEVEL = "playLevel";
    public static final String STATE_SCORE = "playerScore";

    TextView level, score;
    int mLevel=0, mScore=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rotation);

        level = findViewById(R.id.level);
        score = findViewById(R.id.score);

        // onCreate()에서 상태를 저장하는 방법
        // 인스턴스가 생성 혹은 재생성될 때 항상 호출되므로 Bundle이 null 체크를 해야함
        if(savedInstanceState==null) { // 저장 값이 null 일 때

        } else { // 저장 값이 존재할 때
            mLevel = savedInstanceState.getInt(STATE_LEVEL);
            mScore = savedInstanceState.getInt(STATE_SCORE);
            level.setText("레벨 : " +mLevel);
            score.setText("점수 : " +mScore);
        }

    }

    public void onLevelUp(View view) {
        mLevel++;
        level.setText("레벨 : " +mLevel);
    }

    public void onScoreUp(View view) {
        mScore+=100;
        score.setText("점수 : " +mScore);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        //상태 저장
        outState.putInt(STATE_SCORE, mScore);
        outState.putInt(STATE_LEVEL, mLevel);
        //항상 슈퍼클래스의 메소드 호출
        super.onSaveInstanceState(outState);
    }

}

보시는 것과 같이 onSaveInstanceState를 사용해서 Bundle 형태로 데이터를 저장 후,

화면이 회전되면 다시 화면이 onCreate 되기 때문에 그 시점에 저장 값이 있으면 데이터를 다시 불러옵니다.

 

실행화면 입니다.

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

보시는 것과 같이 레벨과 점수를 증가 시키고 화면 회전 시 데이터가 그대로 유지되는 것을 확인할 수 있습니다.

궁금한 점은 언제든지 댓글로 질문해주세요.

감사합니다.