custom arraylist를 sharedpreferences에 저장하기

TinyDB tinydb = new TinyDB(context);
tinydb.putList(“MyUsers”, mUsersArray);
Arraylist를 저장하기 편하게 만든 것이 tinydb이나 실패했다.
https://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences

 

<gson을 라이브러리를 다운받아서 사용> 
https://stackoverflow.com/questions/5418160/store-and-retrieve-a-class-object-in-shared-preference

이때 arralist를 json으로 바꾼 후에 gson을 이용하여 저장이 가능했다.
Type listType = new TypeToken<ArrayList<TeamData>>() {}.getType();
String json = gson.toJson(mTeamDataList, listType);
https://stackoverflow.com/questions/36824536/serialize-arraylist-of-custom-class-to-json-using-gson-and-send-data-over-http
https://stackoverflow.com/questions/24296208/gson-json-to-deserialize-list-of-custom-objects

예제)

data = new ArrayList<Daily>();

// cf : 아마도 이부분은 custom arraylist의 데이터를 json으로 변환하고 이를 preference에 데이터로 넣어주는 것
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Daily>>() {}.getType();
String json = gson.toJson(data, listType);
prefsEditor.putString("cal_data", json);
prefsEditor.commit();

// exp : 가져온 데이터를 출력해준다
public void function2(){ 

   data = new ArrayList<Daily>();
   SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
   Gson gson = new Gson();
   String json = mPrefs.getString("cal_data", "");
   Type myType = new TypeToken<ArrayList<Daily>>() {}.getType();
   ArrayList<Daily> data=gson.fromJson(json, myType);

   // cf : 여기서 얻어온 data값을 가져다가 dailyadapter에서 list에 출력해준다.
   adapter = new DailyAdapter(SecondActivity.this, R.layout.custom_layout, data, textsize);
   lv = (ListView) findViewById(R.id.lv_daily);
   lv.setAdapter(adapter);
   progressbar.setVisibility(View.GONE);


}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s