|
안드로이드 개발 SharedPreferences 객체와 배열 저장을 위한 gson 사용하는 방법 |
|
환경: Android Studio |
안드로이드에서 SharedPreferences 는 모든 Activity 에서 공유 가능한 데이터를 보관하는 곳입니다. 간단한 값은 SQLite 가 아닌 SharedPreferences 을 활용합니다. 그만큼 쉽게 활용할 수 있기 때문입니다. 하지만 저장할 수 있는 데이터타입에 제약이 있습니다. 배열이나 객체를 저장하지 못합니다. 오늘은 SharedPreferences 의 활용 범위를 넓힐 수 있는 gson 라이브러리에 대해 알아 보겠습니다.
|
◎ SharedPreferences 에 객체를 저장하는 방법 |
▼ 방법은 객체를 JSON 으로 변환해서 문자열로 저장하는 것입니다. 그리고 다시 꺼낼 때 gson 을 이용해서 JSON 을 객체로 변환합니다.
▼ 화면은 다음과 같습니다. 상단에 있는 두 에디터에 ID 와 NAME 을 입력하고 저장 버튼을 누르면 SharedPreferences 에 객체로 저장합니다. 그리고 아래로 내려가 자료 불러오기 버튼을 누르면 저장한 객체값을 불러와서 표시합니다.
▼ 객체를 JSON 으로 변환하고 싶다면 gson 에서 제공하는 toJson() 함수를 사용합니다. 첫 번째 인수는 new 로 생성한 객체를 넘기고, 두 번째 인수로 class type 을 넘깁니다. 반환하는 값은 JSON 으로 변환한 String 입니다. SharedPreferences 에 String 값을 저장하면 끝납니다.
protected void onSaveData(View v){
EditText edtId = (EditText)findViewById(R.id.edt_id);
EditText edtName = (EditText)findViewById(R.id.edt_name);
Contact contact = new Contact();
contact.setId(edtId.getText().toString());
contact.setName(edtName.getText().toString());
// Gson 인스턴스 생성
gson = new GsonBuilder().create();
// JSON 으로 변환
String strContact = gson.toJson(contact, Contact.class);
SharedPreferences sp = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("contact", strContact); // JSON으로 변환한 객체를 저장한다.
editor.commit(); //완료한다.
}
▼ 다음은 저장한 JSON 을 SharedPreferences 에서 불러와 다시 객체로 변환합니다. 함수는 fromJson() 함수입니다. 저장할 때 입력한 Id 와 Name 값을 꺼내서 화면에 표시합니다.
protected void onSearchData(View v){
SharedPreferences sp = getSharedPreferences("shared", MODE_PRIVATE);
String strContact = sp.getString("contact", "");
// 변환
Contact contact = gson.fromJson(strContact, Contact.class);
TextView tvId = (TextView)findViewById(R.id.tv_id);
TextView tvName = (TextView)findViewById(R.id.tv_name);
tvId.setText(contact.getId());
tvName.setText(contact.getName());
}
▼ 샘플을 구현한 전체 Activity 는 다음과 같습니다.
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import display.samsung.workplace.model.Contact;
public class SharedPreferencesActivity extends AppCompatActivity {
private Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preferences);
}
protected void onSaveData(View v){
EditText edtId = (EditText)findViewById(R.id.edt_id);
EditText edtName = (EditText)findViewById(R.id.edt_name);
Contact contact = new Contact();
contact.setId(edtId.getText().toString());
contact.setName(edtName.getText().toString());
// Gson 인스턴스 생성
gson = new GsonBuilder().create();
// JSON 으로 변환
String strContact = gson.toJson(contact, Contact.class);
SharedPreferences sp = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("contact", strContact); // JSON으로 변환한 객체를 저장한다.
editor.commit(); //완료한다.
}
protected void onSearchData(View v){
SharedPreferences sp = getSharedPreferences("shared", MODE_PRIVATE);
String strContact = sp.getString("contact", "");
// 변환
Contact contact = gson.fromJson(strContact, Contact.class);
TextView tvId = (TextView)findViewById(R.id.tv_id);
TextView tvName = (TextView)findViewById(R.id.tv_name);
tvId.setText(contact.getId());
tvName.setText(contact.getName());
}
}
▼ Activity 를 구현한 XML 은 다음과 같습니다.
activity_shared_preferences.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"
tools:context="display.samsung.workplace.SharedPreferencesActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#84acd1"
android:layout_margin="5dp"
android:padding="5dp"
android:textColor="#FFFFFF"
android:text="저장할 자료"/>
<EditText
android:id="@+id/edt_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="ID"/>
<EditText
android:id="@+id/edt_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="NAME"/>
<Button
android:id="@+id/btn_save"
android:text="자료 저장"
android:onClick="onSaveData"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#84acd1"
android:layout_margin="5dp"
android:padding="5dp"
android:textColor="#FFFFFF"
android:text="불러온 자료"/>
<TextView
android:id="@+id/tv_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:hint="ID"
android:padding="5dp"/>
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:hint="NAME"
android:padding="5dp"/>
<Button
android:id="@+id/btn_search"
android:text="자료 불러오기"
android:onClick="onSearchData"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
|
◎ SharedPreferences 배열을 저장하는 방법 |
▼ 자료를 저장하는 함수입니다. 객체를 저장하는 방법은 같습니다. 함수 toJson() 을 사용해서 JSON String 문자로 변환합니다.
protected void onSaveData(View v){
Contact contact1 = new Contact();
contact1.setId("id1");
contact1.setName("name1");
Contact contact2 = new Contact();
contact2.setId("id2");
contact2.setName("name2");
List<Contact> datas = new ArrayList<Contact>();
datas.add(contact1);
datas.add(contact2);
gson = new GsonBuilder().create();
Type listType = new TypeToken<ArrayList<Contact>>() {}.getType();
String json = gson.toJson(datas, listType);
SharedPreferences sp = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("contacts", json); // JSON으로 변환한 객체를 저장한다.
editor.commit(); //완료한다.
}
▼ 저장한 값을 다시 불러와서 로그에 출력하는 함수 입니다. 콘솔에 저장한 값이 제대로 출력이 되네요.
protected void onSearchData(View v){
SharedPreferences sp = getSharedPreferences("shared", MODE_PRIVATE);
String strContact = sp.getString("contacts", "");
Type listType = new TypeToken<ArrayList<Contact>>() {}.getType();
// 변환
List<Contact> datas = gson.fromJson(strContact, listType);
for (Contact data : datas) {
Log.d("PRINT", data.getId());
Log.d("PRINT", data.getName());
}
}
'안드로이드 개발' 카테고리의 다른 글
| 안드로이드 개발 간단하게 위젯 만드는 방법 (0) | 2018.08.15 |
|---|---|
| 안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법 (3) | 2018.08.07 |
| 안드로이드(Android) 개발 Timer 구현하는 방법 (0) | 2018.07.05 |
| 안드로이드 개발 인터넷 연결(WI-FI, 3G, 4G) 구분해서 연결 확인하는 방법 (0) | 2018.07.02 |
| 안드로이드 개발 에뮬레이터 앱 db 조회 하는 방법 (0) | 2018.04.11 |
| 안드로이드 개발 Android GPS 정보 알아오기 (63) | 2018.04.07 |
| 안드로이드 콘솔에서 adb shell 에러 해결하는 방법 (0) | 2018.03.30 |
| 안드로이드 개발 자료 관리를 위한 SharedPreferences 사용하는 방법 (0) | 2018.03.24 |
