Android : Saving arraylist of strings using sharedPreferences

on Wednesday, July 30, 2014


So I have a list , which I want every item in that list to have a separate settings/options , anyways The saving and loading using shared preferences works great and all the problem is every item in that list has the same options!


so I thought Id use the item name as a save EXTRA and load/save using that name since the user can't enter the same name for two items.


here's the code:



public void SaveNotes(){

try{
SharedPreferences settings = getActivity()
.getSharedPreferences(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.clear();

editor.putInt(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME), mDescriptionOfNote.size());

for(int i = 0; i < mDescriptionOfNote.size(); i++){

editor.remove(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME) + i);
editor.putString(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME) + i, mDescriptionOfNote.get(i));
}

editor.commit();

}

catch(Exception e){

Toast.makeText(getActivity(),
"There was an Error while trying to Save Data", Toast.LENGTH_LONG).show();

}


}

public void LoadNotes(){

try{

SharedPreferences settings = getActivity().getSharedPreferences(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME), Context.MODE_PRIVATE);

mDescriptionOfNote.clear();

int size = settings.getInt(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME), 0);

for(int i =0; i<size; i++){

mDescriptionOfNote.add(settings.getString(getActivity()
.getIntent().getStringExtra(EXTRA_FILENAME) + i, null));

}

}catch(Exception e){

Toast.makeText(getActivity(),
"There was an Error while trying to Load Data", Toast.LENGTH_LONG).show();

}

}


sorry for the messy code but I was trying to get it to work but nothing works.


the:



getActivity().getIntent().getStringExtra(EXTRA_FILENAME)


is the list's item name which was passed to the fragment.


0 comments:

Post a Comment