-1

How can I convert an XML Drawable file from the drawable folder into a String? I'm trying to store the drawable in SQL Lite in string format.

AtomicallyBeyond
  • 348
  • 1
  • 15
  • Why do you want to convert drawable to string? – Andrii Hridin Sep 16 '21 at 08:53
  • What is the purpose for this ? – Pratik Banodkar Sep 16 '21 at 09:03
  • As in, retrieve the original XML (if so, you should clarify this)? I'm not certain that's possible. – Ryan M Sep 16 '21 at 09:26
  • You'd probably want to retrieve the XML Drawable too, so start from that. Storing it into the database is just an opposite of that. As usual [the documentation](https://developer.android.com/reference/android/graphics/drawable/Drawable#createFromStream(java.io.InputStream,%20java.lang.String)) will tell you that you can create a Drawable from an InputStream and that seems to be the only way not Involving the resources or a file path. So, if you can somehow hack input/output streams to generate/read Strings then that could work. – Markus Kauppinen Sep 16 '21 at 10:28
  • 1
    Related to the vague idea above: [Serialize object with outputstream](https://stackoverflow.com/questions/8240701/serialize-object-with-outputstream/8240779) and [How do I convert a String to an InputStream in Java?](https://stackoverflow.com/questions/782178/how-do-i-convert-a-string-to-an-inputstream-in-java). – Markus Kauppinen Sep 16 '21 at 10:58

1 Answers1

1

You can follow these steps:

  1. Convert your Drawable to a Bitmap: Converting an image from drawable to byte array in Android (via an intermediate Canvas).
  2. Convert your Bitmap to byte[]: Drawable to byte[] (well it says Drawable to byte[] but it really solves the problem of converting only a BitmapDrawable to a byte[] via its contained Bitmap).
  3. Store the byte[] as a BLOB to SQL Lite, or convert it first to a hex String and then store it.

This question then should be a possible duplicate of all those steps together.

I don't know a cleaner way to do it rather than converting first to byte[].


Example loseless encoding and storing:

  1. Read Drawable from Resources.
  2. Convert Drawable to a Bitmap (use intrinsic dimensions).
  3. Compress Bitmap to byte[] in Bitmap.CompressFormat.PNG format.
  4. Store in SQL Lite as BLOB, or first convert byte[] to hex String and then store it.

Example loseless restoring and decoding:

  1. Read from SQL Lite (and convert hex string to byte[] if you stored it as string).
  2. Decode byte[] to a Bitmap using a ByteArrayInputStream (for images less than about 2 GiBs in size) via BitmapFactory.decodeStream method.
  3. Create a Drawable using the decoded Bitmap (use a BitmapDrawable for this).
gthanop
  • 3,035
  • 2
  • 10
  • 27