Ganesh
Ganesh

Reputation: 1919

How to save Arraylist of Objects from Fragment class into SharedPreferencess

I saw similar questions in stackoverflow ( LINK , LINK ) and other websites . They are doing everything from an Activity hence they didn't get problem.

I have an Activity and Fragment class. I am trying to save ArrayList of Object into shared preferences from a Fragment. Below is what i tried

            SharedPreferences prefs = getActivity().getSharedPreferences("SHARED_PREFS_FILE", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            try {
               editor.putString("taggedFriends",ObjectSerializer.serialize(taggableFriends));

            } catch (IOException e) {
                e.printStackTrace();

Its showing error at ObjectSerializer

**Cannot resolve symbom 'ObjectSerializer'** 

I tried

getActivity.ObjectSerializer.serialize(..);

But error didn't go. Help me what can i do now.

Thankyou for spending time for me.

Upvotes: 1

Views: 871

Answers (2)

Fabio Venturi Pastor
Fabio Venturi Pastor

Reputation: 2529

Try this:

Last edit:

In this case:

 static class YourObject
{
    private String _name;

    public YourObject(String name)
    {
        this._name = name;  
    } 
}


YourObject yourObject = new YourObject(myName);
ArrayList<YourObject> foo = new ArrayList<YourObject>();
foo.add(yourObject);

convert an ArrayList to JSONArray:

  JSONArray mJSONArray = new JSONArray(foo);

Then save the JSONArray:

 SharedPreferences.Editor editor = prefs.edit();
 editor.putString("yourStringName", mJSONArray.toString());

String to JSONArray:

SharedPreferences prefs = getSharedPreferences("SHARED_PREFS_FILE",   Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("yourStringName", "");
JSONArray jsonArray = new JSONArray(myJSONArrayString);

JSONArray to ArrayList:

ArrayList<String> list = new ArrayList<String>();     
   for (int i=0;i<jsonArray.length();i++){ 
    list.add(jsonArray.get(i).toString());
   } 

I hope this solve your question.

Upvotes: 1

savepopulation
savepopulation

Reputation: 11921

First add Gson to your gradle:

compile 'com.google.code.gson:gson:2.2.4'

Convert your list to Json String like below:

List<String> foo = new ArrayList<String>();
foo.add("Item1");
foo.add("Item2");
foo.add("Item3");

String json = new Gson().toJson(foo );

And save it to shared pref like below:

SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("yourKey", json);

And when you want to use read your saved json string from pref:

String json = mPrefs.getString("yourKey", "");

Convert your Json String to list of your objects like below. In example i used String.

ArrayList<String> foo = (ArrayList<String>) new Gson().fromJson(json,
                    new TypeToken<ArrayList<String>>() {
                    }.getType());

Upvotes: 1

Related Questions