본문 바로가기
IT Study/Android

[Android] SharedPreferences를 이용한 데이터 저장

by dev_huhu 2019. 11. 1.
반응형

안드로이드 프로젝트를 진행하면서 DB에 저장하긴 낭비라고 생각되는 간단한 정보를 저장할 경우 SharedPreferences를 사용해보자 (환경변수, 아이디, 등 앱이 종료되어도 사라지면 안될 정보)

context 부분이 오류가 날 경우: getContext(), getApplicationContext() 등
사용중인 액티비티나 프래그먼트의 context를 넣어주면됨

 

  • 값 불러오기
 //"com.example.myapplication"은 본인 프로젝트의 pakage name으로 대체
 SharedPreferences sharedPreferences;
 sharedPreferences = context.getSharedPreferences("com.example.myappication",this.MODE_PRIVATE);
 String value1 = sharedPreferences.getString("key1", null);

 

  • 값 수정/입력하기
 SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("key1","value1"); // key, value
        editor.commit(); // 최종 commit

 

  • 값 삭제하기
sharedPreferences = getSharedPreferences("com.example.application", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove("key1");
        editor.commit();

 

  • 값 모두 삭제하기
sharedPreferences = context.getSharedPreferences("com.example.application", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();

 

반응형

댓글