如何存储的HashMap在Android? [英] How to store HashMap on Android?

查看:294
本文介绍了如何存储的HashMap在Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想的HashMap 存储在Android上。我认为这是最好使用内部存储,但我不明白如何保存的HashMap 在它的再后来读的。有人能解释该怎么做正确吗?

有计数器,用自己的名字和值。我想加载它们onсe当一些活动已经开始,与他们合作(更改,删除,增加新的),然后将数据保存到下一次使用。现在,我使用HashMap的,因为它很容易删除/添加值。

 的HashMap<字符串,整数>柜台;
 

解决方案

共享preferences还可以存储在键值对数据的HashMap,那么为什么不得到所有键值的HashMap和存储到地图,因为它

 共享preferences preF =的getContext()。getShared preferences(Your_Shared_ preFS),
                                                           Context.MODE_PRIVATE);
共享preferences.Editor编辑器= pref.edit();

    对于(字符串S:map.keySet()){
        editor.putString(S,map.get(多个));
    }
 

要获取的值,你可以使用:

 公共抽象地图<字符串,> GETALL()
 

http://developer.android.com/reference/android/content/Shared$p$pferences.html#getAll%28%29

使用:

 共享preferences preF =的getContext()。getShared preferences(Your_Shared_ preFS),
                                                           Context.MODE_PRIVATE);
HashMap的<字符串,字符串>地图= HashMap的<字符串,字符串> pref.getAll();
对于(字符串S:map.keySet()){
        字符串值= map.get(S);
        //使用价值
    }
 

code未编译,所以它可能有一些小错误,但应该工作。

So, I'm trying to store HashMap on Android. I think it's better to use internal storage, but I don't understand how to save HashMap in it and then read it later. Can someone explain how to do that properly, please?

There are counters with their own names and values. I want to load them onсe when some activity was started, work with them (change, delete, add new), and then save that data to use next time. Right now I use HashMap because it's easy to delete/add values.

HashMap<String, Integer> counters;

解决方案

SharedPreferences also store data in key-value pair as hashmap, so why not get all key-values from hashmap and store into map, as it:

SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"), 
                                                           Context.MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();

    for (String s : map.keySet()) {
        editor.putString(s, map.get(s));
    }

To fetch values you can use:

public abstract Map<String, ?> getAll ()

http://developer.android.com/reference/android/content/SharedPreferences.html#getAll%28%29

use:

SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"), 
                                                           Context.MODE_PRIVATE);
HashMap<String, String> map= HashMap<String, String> pref.getAll();
for (String s : map.keySet()) {
        String value=map.get(s);
        //Use Value
    }

Code is not compiled, so it may have some minor errors, but should work.

这篇关于如何存储的HashMap在Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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