3

I need to find a way of saving a HashMap to string to save in my SQLite database to retrieve on 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 i get an error under put at contentValues.put with this error:

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

So my question is how can i convert that to a string so that i can save it into my sqlite database?

Thanks

  • 1
    Can you explain a bit more? **WHY** do you want to save hashmap? Do you want to save a key String and value bitmap in different rows? – MysticMagicϡ Dec 24 '14 at 05:45
  • Try `myMarkersHash.toString();` – Darshan Lila Dec 24 '14 at 05:45
  • @MagicalPhoenixϡ: Sorry, yes i have an app where i take a photo and return the the map (google maps v2) as a marker, now the problem i am having is that i need to save all that data so when the user leave the map and returns all should still be there. So i was told to use SQlite databse for that, so am struggling here cause i still need to save the image as well and this is the first time i am using SQlite, so please excuse me if i ask really stupid questions :-) –  Dec 24 '14 at 05:49
  • 1
    you cannot store hashmap into database directly. you will require separate table or configure it in that way like hibernate provide mapping collection to table. – Manoj Sharma Dec 24 '14 at 05:49

1 Answers1

5

You can store your HashMap in your Database by converting it into String using Gson library. This library will convert your object to String and you will get back that object whenever you want it.
Link to Download Lib : https://code.google.com/p/google-gson/


Convert Object into String :

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


Convert String into Object :

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


Check this example as well : http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html

Deep Mehta
  • 1,237
  • 2
  • 11
  • 17