0

I want to save an object(of type MyObject) in Shared Preference via gson:

PS: store and retrieve a class object in shared preference

So 1 of the fields in MyObject is an ImageView which is fetched from a url.

Now when I do:

String json = gson.toJson(myObject);

I get a stackoverflow error. When I comment out the ImageView from my MyObject POJO this error gets resolved.

Q1- There are barely 8-10 images. So how do I store them through gson??

Q2- And is it a good practise to store images through gson, if not so then what better option do I have?

I think the error comes due to converting ImageView to string.

Community
  • 1
  • 1
Pranav Mahajan
  • 2,048
  • 2
  • 23
  • 36

1 Answers1

1

You store data that can be converted to string or numbers (long, int ...) in gson/sharedpreferences.

you can't and you shouldn't store ImageView because it is a UI object that is meant to be used to display Images in android layout.

With that being said, try saving your actual Image to a private directory that belongs to your app instead of this.

try {
   Bitmap bmp = yourImageView.getDrawingCache();
   FileOutputStream out = new FileOutputStream(pathToOutputFile);
   bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
   out.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

For more about storage in android : Storage Guide

Mr.Me
  • 9,192
  • 5
  • 39
  • 51