본문 바로가기

안드로이드 개발/Activity

안드로이드 화면 회전시 데이터 보존

반응형
안드로이드 화면 회전시 OnDestory(), OnCreate()등이 호출 되면서 기존의 변수들이 모두 초기화 되어 버린다.
이러한 데이터 초기화를 방지하기 위해 화전회전시 onRetainNonConfigurationInstance()이 호출 되는데 이때,
데이터를 저장하여 화면회전후 다시 불러오는 방법이다.

@Override
public Object onRetainNonConfigurationInstance() 
{		
        //HashMap을 이용하여 데이터를 저장
        HashMap data= new HashMap();
        data.put("year", year);
        data.put("month", month);
        return data;
}


@SuppressWarnings("unchecked")
private void restore() 
{
       //데이터를 불러온다.
       Object obj = getLastNonConfigurationInstance();
       if(obj!=null)
       {
           HashMapdata = (HashMap) obj;
           this.year = Integer.parseInt(data.get("year").toString());
           this.month = Integer.parseInt(data.get("month").toString());
       }
}


반응형