안드로이드 스튜디오 앱 개발/실제 앱 개발 과정

[Android Studio] SharedPreferences로 아이템을 저장하고 For문을 이용하여 저장했던 모든 아이템 조회하기 - 망댕이의 앱 개발

망댕이 2024. 4. 16. 12:16
반응형
반응형

 

단순하게 SharedPreferences를 이용하여 하나의 text를 저장하고 불러오는 것은 정말 쉽습니다.

하지만 수많은 text들을 저장하고 그것들을 하나씩 조회하는 방법은 For문과 고유의 count 값이 필요합니다.

 

    private static final String PREF_NAME = "MyPreferences";
    private static final String KEY_COUNT = "count";
    private static final String KEY_TITLE = "title";
    private static final String KEY_CONTENT = "content";
    SharedPreferences sharedPreferences;


                 --생략--


                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
                            String title = editText_title.getText().toString(); //저장할 title 정보
                            String content = editText_content.getText().toString(); //저장할 content 정보
                            int itemCount = sharedPreferences.getInt(KEY_COUNT, 0);

                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString(KEY_TITLE + itemCount, title);
                            editor.putString(KEY_CONTENT + itemCount, content);
                            editor.putInt(KEY_COUNT, itemCount + 1);
                            editor.apply();
                        }
 

onClick()을 실행하면 editText에서 각각 text를 가져와 title과 content에 할당하고 SharedPreferences를 이용하여 저장하는 것을 볼 수 있습니다. 하지만 putString( key, value ) 에서 key 값에 + itemCount가 있는데요. 이것은 각각 title 과 content를 저장할 때 서로 다른 고유 key 값을 부여하기 위해서입니다.

그래서 저장할 때 마다 itemCount 값이 1씩 증가하게 되면서 서로 다른 Key값을 가지게 됩니다.

 

 

그리고 SharedPreferences로 title과 content를 모두 저장했으니 조회를 해야하는데요.

    private static final String PREF_NAME = "MyPreferences";
    private static final String KEY_COUNT = "count";
    private static final String KEY_TITLE = "title";
    private static final String KEY_CONTENT = "content";
    SharedPreferences sharedPreferences;

           --생략--



private List<Content> loadData() {
        List<Conteㅊnt> itemList = new ArrayList<>();
        sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);

        // SharedPreferences에서 데이터 읽어오기
        int itemCount = sharedPreferences.getInt(KEY_COUNT, 0);
        for (int i = 0; i < itemCount; i++) {
            String titleKey = KEY_TITLE + i;
            String contentKey = KEY_CONTENT + i;
            String title = sharedPreferences.getString(titleKey, "");
            String content = sharedPreferences.getString(contentKey, "");
            itemList.add(new Content(title, content));
        }

        return itemList;
    }
 

loadData()를 따로 만들어서 getString()을 이용하여 정보를 조회해보았습니다.

sharedPreferences.getInt(KEY_COUNT, 0)로 현재 저장한 개수를 itemCount에 할당하고 For문을 이용하여 itemCount까지 반복하여 title과 content를 가져올 수 있었습니다.

 

그리고 가져온 title과 content는 Content형의 List 배열에 추가하고 추가 코드를 통해 recyclerView에 title 과 content가 하나의 아이템으로 보여질 수 있도록 만들어 저장, 조회 기능을 구현할 수 있었습니다.

 

 
반응형