Java – How do I convert a Hashmap to a String to save in a SQLite database?

How do I convert a Hashmap to a String to save in a SQLite database?… here is a solution to the problem.

How do I convert a Hashmap to a String to save in a SQLite database?

I need to find a way to save the HashMap into a string to save in my SQLite database to retrieve at a later stage.

Here is my HashMap :

private Map<String, Bitmap> myMarkersHash new HashMap<String, Bitmap>();

Then when saving to the SQlite database:

contentValues.put(LocationsDB.FIELD_HASH, myMarkersHash);

But the problem is that I get the error message under the put of contentValues.put:

The method put(String, String) in the type ContentValues is not applicable for the arguments (String, Map<String,Bitmap>)

So my question is how to convert it to a string so that it can be saved to my sqlite database?

Thanks

Solution

You can use the Gson library to convert a HashMap to a string, which you can store in a database.
The library converts your object to a string, and you can get it back at any time.
Download library link: https://code.google.com/p/google-gson/

To convert an object to a string:

Gson objGson= new Gson();
String strObject = objGson.toJson(myMarkersHash);
Bundle bundle = new Bundle();
bundle.putString("key", strObject);

To convert a string to an object:

Gson gson = new Gson();
Type type = new TypeToken<Model>() {}.getType();
myMarkersHash = gson.fromJson(bundle.getString("key"), type);

Also check this example: http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html

Related Problems and Solutions