AOS

SharedPreferences로 ArrayList 저장

asu2880 2020. 2. 19. 23:43

SharedPreferences에 ArrayList 형식의 데이터를 저장하는 방법


SharedPreferences는 1개의 키에 대해서 1개의 String을 저장합니다.
하지만 1개의 Key에 대해서 ArrayList 형식의 데이터를 저장하고 싶을 때가 있습니다.
Json을 이용하면 ArrayList 형식의 데이터를 SharedPreferences에 저장할 수 있습니다.
ArrayList의 데이터를 Json형식으로 변환하여 1개의 String으로 만든 후 이를 SharedPreferences에 저장할 수 있습니다.
반대로 읽을 때는 Json 형식의 String을 읽어와 다시 ArrayList로 변환하면 됩니다.
아래 코드 setStringArrayPref는 ArrayList를 Json으로 변환하여
SharedPreferences에 String을 저장하는 코드입니다. 
getStringArrayPref는 SharedPreferences에서 Json형식의 String을 가져와서
다시 ArrayList로 변환하는 코드입니다.

MainActivity.java

package com.asukim.sharedpreferencesarraylistsave;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    TextView textView;
    EditText editText;
    Button button;

    ArrayAdapter<String> adapter;
    ArrayList<String> array = new ArrayList<>();

    // ArrayList -> Json으로 변환
    private static final String SETTINGS_PLAYER_JSON = "settings_item_json";

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

        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
        listView = (ListView) findViewById(R.id.listView);
        textView = (TextView) findViewById(R.id.textView);

        array = getStringArrayPref(getApplicationContext(), SETTINGS_PLAYER_JSON);

        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String str = array.get(position);
                textView.setText(str);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = editText.getText().toString();
                if (str.length() != 0) {
                    array.add(str + "");
                    adapter.notifyDataSetChanged();

                    editText.setText("");
                }
            }
        });
    }


    private void setStringArrayPref(Context context, String key, ArrayList<String> values) {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray a = new JSONArray();

        for (int i = 0; i < values.size(); i++) {
            a.put(values.get(i));
        }

        if (!values.isEmpty()) {
            editor.putString(key, a.toString());
        } else {
            editor.putString(key, null);
        }

        editor.apply();
    }

    private ArrayList getStringArrayPref(Context context, String key) {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String json = prefs.getString(key, null);
        ArrayList urls = new ArrayList();

        if (json != null) {
            try {
                JSONArray a = new JSONArray(json);

                for (int i = 0; i < a.length(); i++) {
                    String url = a.optString(i);
                    urls.add(url);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }

    @Override
    protected void onPause() {
        super.onPause();

        setStringArrayPref(getApplicationContext(), SETTINGS_PLAYER_JSON, array);
        Log.d(TAG, "Put json");
    }
}

activity_main.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"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_toLeftOf="@+id/button"
            android:hint="input keyword" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="add" />
    </RelativeLayout>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Git

 

asukim1022/SharedPreferencesArrayListSaveApp

Contribute to asukim1022/SharedPreferencesArrayListSaveApp development by creating an account on GitHub.

github.com


스크린샷

728x90
반응형

'AOS' 카테고리의 다른 글

changing Floating Action Button color  (0) 2020.02.26
Bitmap -> String 변환, String -> Bitmap 변환  (0) 2020.02.23
SharedPreferences  (0) 2020.02.18
preview 화면 안나오는 오류 해결  (0) 2020.02.09
TabLayout  (0) 2020.02.05