我怎么能存储数据结构,比如在Android的内部一个HashMap? [英] How can I store a data structure such as a Hashmap internally in Android?

查看:147
本文介绍了我怎么能存储数据结构,比如在Android的内部一个HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序,我想存储地图结构,例如:地图<字符串,地图<字符串,字符串>> 使用内部存储。我已经研究过使用共享preferences ,但如你所知,存储原始数据类型时,这仅适用。我试图用的FileOutputStream ,但它只是让我写字节...我需要以某种方式序列化HashMap和再写入文件?

In my Android application I'm trying to store a Map structure such as:Map<String, Map<String, String>>using internal storage. I've looked into using SharedPreferences, but as you know, this only works when storing primitive data types. I tried to use FileOutputStream, but it only lets me write in bytes...Would I need to somehow serialize the Hashmap and then write to file?

我试图通过读取HTTP://开发商。 android.com/guide/topics/data/data-storage.html#filesInternal 但我似乎无法找到我的解决方案。

I've tried reading through http://developer.android.com/guide/topics/data/data-storage.html#filesInternal but I can't seem to find my solution.

下面是什么,我试图做一个例子:

Here's an example of what I'm trying to do:

private void storeEventParametersInternal(Context context, String eventId, Map<String, String> eventDetails){

Map<String,Map<String,String>> eventStorage = new HashMap<String,Map<String,String>>();
Map<String, String> eventData = new HashMap<String, String>();
String REQUEST_ID_KEY = randomString(16);
.   //eventData.put...
.   //eventData.put...
eventStorage.put(REQUEST_ID_KEY, eventData);
FileOutputStream fos = context.openFileOutput(EVENT_FILENAME, Context.MODE_PRIVATE);
fos.write(eventStorage) //This is wrong but I need to write to file for later access..

}

什么是用于存储这种类型的内部数据结构中的Andr​​oid应用程序的最佳方法?很抱歉,如果这似乎是一个愚蠢的问题,我是很新的Andr​​oid系统。先谢谢了。

What is the best approach for storing this type of a data structure internally in an Android App? Sorry if this seems like a dumb question, I am very new to Android. Thanks in advance.

推荐答案

的HashMap 是序列化的,所以你可以只使用一个的的FileInputStream 和的FileOutputStream ObjectInputStream的和<一href="http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream.

HashMap is serializable, so you could just use a FileInputStream and FileOutputStream in conjunction with ObjectInputStream and ObjectOutputStream.

要编写的HashMap 到一个文件:

FileOutputStream fileOutputStream = new FileOutputStream("myMap.whateverExtension");
ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream);

objectOutputStream.writeObject(myHashMap);
objectOutputStream.close();

要读的HashMap 从文件:

FileInputStream fileInputStream  = new FileInputStream("myMap.whateverExtension");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

Map myNewlyReadInMap = (HashMap) objectInputStream.readObject();
objectInputStream.close();

这篇关于我怎么能存储数据结构,比如在Android的内部一个HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆