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.
Asked
Active
Viewed 124 times
-1
-
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
-
1Related 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 Answers
1
You can follow these steps:
- Convert your
Drawableto aBitmap: Converting an image from drawable to byte array in Android (via an intermediateCanvas). - Convert your
Bitmaptobyte[]: Drawable to byte[] (well it says Drawable to byte[] but it really solves the problem of converting only a BitmapDrawable to abyte[]via its containedBitmap). - Store the
byte[]as a BLOB to SQL Lite, or convert it first to a hexStringand 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:
- Read
DrawablefromResources. - Convert
Drawableto aBitmap(use intrinsic dimensions). - Compress
Bitmaptobyte[]inBitmap.CompressFormat.PNGformat. - Store in SQL Lite as BLOB, or first convert
byte[]to hexStringand then store it.
Example loseless restoring and decoding:
- Read from SQL Lite (and convert hex string to
byte[]if you stored it as string). - Decode
byte[]to aBitmapusing aByteArrayInputStream(for images less than about 2 GiBs in size) viaBitmapFactory.decodeStreammethod. - Create a
Drawableusing the decodedBitmap(use aBitmapDrawablefor this).
gthanop
- 3,035
- 2
- 10
- 27