0

I want to save Hashset Object in to Sharedpreference and than want retrieve that data. I am storing data in to hashset and and converting object in to json using Gson. Actually m storing bitmap in to Hashset. I am able to convert and save Hashsetobject into sharedpreference. I am getting problem when I am retrieving and converting json to Hashset Object.

HashSet<images> img = new HashSet<images>(CIRCLES_LIMIT);

Here is Method For Saving Object in to Sharedpreference.

  public void saveString() throws JSONException {

    Object spSquare = c.getStringDrawObjImages();


    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    SharedPreferences.Editor editor = sharedPrefs.edit();
    Gson gson = new Gson();


    String jsonSquare = gson.toJson(spSquare)
    editor.putString("kEySquare", jsonSquare);
    editor.commit();

}

Method For Retrieving That Object.

   public void openString() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    Gson gson = new Gson();

    String jsonSquare=sharedPrefs.getString("kEySquare",null);



  Type typeSquare = new TypeToken<HashSet<images>>(){}.getType();
    HashSet<images> arrayListSquare = gson.fromJson(jsonSquare,typeSquare);`//getting Exception here jsonSyntax Error`


    if (arrayListSquare != null) {
        img = arrayListSquare;
    }
}
Nikhil
  • 3,711
  • 8
  • 32
  • 43
Nitin Thakor
  • 535
  • 3
  • 15
  • share your json – Nikhil Sep 28 '16 at 08:54
  • { "img": "[Circle[218.69626, 475.58936, 0,android.graphics.Bitmap@42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,], Circle[186.74065, 670.43713, 0,android.graphics.Bitmap@42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,]]" } – Nitin Thakor Sep 28 '16 at 08:56

2 Answers2

1

As per your comment your json as follows is not in format so that Gson can parse it as you are receiving your circle attribute in string not as json.

{
  "img": "[Circle[218.69626, 475.58936, 0,android.graphics.Bitmap@42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,]‌​, Circle[186.74065, 670.43713, 0,android.graphics.Bitmap@42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,]‌​]"
}

So your Json is received as object having only attribute that is img.

and you are parsing it as array. That's error. So contact your back end developer and change json structure accordingly.

Nikhil
  • 3,711
  • 8
  • 32
  • 43
1

You serialise a object and want to deserialise it into a HashSet. That's the problem.

Object spSquare = c.getStringDrawObjImages();

What's the type of spSquare? Suppose it is 'Foo.class', you should deserialise it like this:

Foo foo = gson.fromJson(jsonString, Foo.class);

'foo.img' should be your HashSet

Benny Huo
  • 390
  • 1
  • 2
  • 11
  • You should find out the right class. What on earth is the type of spSquare ? It seems to have only one field in it which is 'img', and the field 'img' turn out to be your HashSet, isn't it? – Benny Huo Sep 28 '16 at 12:46