当前位置:首页 > 数据库 > SQlite

如何将Hashmap转换为String以保存在SQLite数据库中?

我需要找到一种方法来将HashMap保存为字符串以保存在我的SQLite数据库中以便在以后的阶段进行检索.

这是我的HashMap:

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

然后保存到SQlite数据库时:

contentValues.put(LocationsDB.FIELD_HASH, myMarkersHash);

但问题是我在contentValues.put下输入错误时出现此错误:

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

所以我的问题是如何将其转换为字符串,以便我可以将其保存到我的sqlite数据库?

谢谢

解决方法:

您可以使用Gson库将HashMap转换为String,从而将HashMap存储在数据库中.
该库将您的对象转换为String,您可以随时获取该对象.
链接到下载Lib:https://code.google.com/p/google-gson/

将对象转换为字符串:

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

将String转换为Object:

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

也请查看此示例:http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!