【问题标题】:How to Store Hashmap to android so that it will be reuse when application restart using shared preferences?如何将 Hashmap 存储到 android,以便在使用共享首选项重新启动应用程序时重用它?
【发布时间】:2012-08-09 12:45:48
【问题描述】:

我想将 hashmap 存储到我的 android 应用程序中,当重新启动时,它会显示最后保存的 hashmap 值。

HashMap<Integer,String> HtKpi=new HashMap<Integer,String>(); 

是我的哈希图,其中动态存储了 44 个值。这很好用!!! 现在,我想存储它以备将来使用(应用程序重新启动或重用)。

【问题讨论】:

标签: java android hashmap sharedpreferences


【解决方案1】:

使用 Raghav,我创建了一个完整的工作示例:

public class AppCache {
public static HashMap<String, String> hashMap = null;

/* REPOSITORY NAME */
public static final String REPOSITORY_NAME = "HMIAndroid_System_Settings";

/* SETTINGS */
public static final String SETTING_PLANNED = "DATA_PLANNED";
public static final String SETTING_ACTUAL = "DATA_ACTUAL";
public static final String SETTING_ETA = "DATA_ETA";
public static final String SETTING_OR = "DATA_OR";
public static final String SETTING_LINEID = "LINEID";
public static final String SETTING_SERVERIP = "SERVERIP";

public static void LoadSettings(Context context) {
    SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
    hashMap = (HashMap<String, String>) pref.getAll();
    if(hashMap == null) {
        hashMap = new HashMap<String, String>();
    }
}

public static void SaveSettings(Context context) {
    if(hashMap == null) {
        hashMap = new HashMap<String, String>();
    }

    //persist
    SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    for (String s : hashMap.keySet()) {
        editor.putString(s, hashMap.get(s));
    }
    editor.commit();
}
}

然后在你的 onCreate 中加载它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //load settings
    AppCache.LoadSettings(getApplicationContext());
    Log.d("onCreate","My LineID=" + AppCache.hashMap.get(AppCache.SETTING_LINEID));
    Log.d("onCreate","Dest ServerIP=" + AppCache.hashMap.get(AppCache.SETTING_SERVERIP));
}

随时随地在您的应用更新设置中:

AppCache.hashMap.put(AppCache.SETTING_LINEID, "1");
AppCache.hashMap.put(AppCache.SETTING_SERVERIP, "192.168.1.10");

在你的 onDestroy 保存设置到缓存:

@Override
protected  void onDestroy() {
    //save settings
    AppCache.SaveSettings(getApplicationContext());
}

【讨论】:

【解决方案2】:

对其进行序列化并将其保存在共享首选项或文件中。当然,您能否做到这一点取决于映射自和映射到的数据类型。 (例如,如果您尝试序列化视图,这将不起作用。)

例子:

//persist
HashMap<String, Integer> counters; //the hashmap you want to save
SharedPreferences pref = getContext().getSharedPreferences("Your_Shared_Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();    
for (String s : counters.keySet()) {
    editor.putInteger(s, counters.get(s));
}
editor.commit();


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

【讨论】:

  • 我添加了一些示例代码。请注意,这是我的头等大事,可能行不通。
  • public abstract Map getAll () 我在这一行遇到错误
  • 对不起。那不应该在那里。
【解决方案3】:

您可以将其序列化为 json 并将生成的字符串存储在首选项中。然后当应用程序重新启动时,从首选项中获取字符串并对其进行反序列化。

编辑:

为此,您可以使用 Google Gson 例如。

您需要将地图包装在一个类中:

public class MapWrapper {
  private HashMap<Integer, String> myMap;
  // getter and setter for 'myMap'
}

要存储地图:

Gson gson = new Gson();
MapWrapper wrapper = new MapWrapper();
wrapper.setMyMap(HtKpi);
String serializedMap = gson.toJson(wrapper);
// add 'serializedMap' to preferences

要检索地图:

String wrapperStr = preferences.getString(yourKey);
MapWrapper wrapper = gson.fromJson(wrapperStr, MapWrapper.class);
HashMap<Integer, String> HtKpi = wrapper.getMyMap(); 

【讨论】:

  • 您的评论是寻求帮助吗?
  • ya..我需要更多帮助来解决这个问题
  • 在不告诉您遇到的问题的情况下如何获得帮助?
  • 对不起.. 请帮助我进行哈希表存​​储...无论如何我都想存储哈希表存储...并希望在表格布局中显示它..可能是(1)存储哈希表并再次将其传输到哈希表中以在表格布局中显示它..有点像我这样想..
  • @KayKay 你能告诉我 getMyMap() 方法的逻辑是什么,是简单的 getter-setter 还是其他需要处理的事情?
【解决方案4】:

我有一个解决方案。我在我的应用程序中做过同样的事情,我想将状态名称存储为键,将状态缩写存储为值。为此在“res/values/string.xml”中声明了一个字符串数组。这是用于声明数组的代码:

 <string-array name="array_string">
    <item>yourKey1;yourValue1</item>
    <item>yourKey2;yourValue2</item>
    <item>yourKey3;yourValue3</item>
</string-array>

然后,在您想要实例化哈希图的地方,执行以下操作:

HashMap<String, String> map = new HashMap<String, String>();
    Resources res = getResources();

    String[] stringArray = res.getStringArray(R.array.array_string);

    //R.array.array_string is the name of your array declared in string.xml
    if(stringArray == null || stringArray.length == 0) return;

    for(String string : stringArray) {
        String[] splittedString = string.split(";");
        if(splittedString.length > 0) {
            String key = splittedString[0];
            String value = splittedString[1];
            map.put(key, value);
        }
    }

现在您已经准备好使用 HaspMap 实例了。这是我喜欢的简单方法。

【讨论】:

  • 我已经准备好了 hashmap.. 没问题....
  • 是的,我明白你想做什么。但是在这里我正在做的是存储数组,并且在运行时我正在创建 hashmap 的实例而不是存储它。无论如何,这正是我所做的,如果您找到任何其他解决方案,请在此处发布。这样我也可以试试。
【解决方案5】:
   @Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
}

你可以把它存储在这里.... 这个方法在一个 Activity 可能被杀死之前被调用,这样当它在未来某个时间回来时它可以恢复它的状态。

然后你可以从这里收回它,,,

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onRestoreInstanceState(savedInstanceState);
}

当活动从先前保存的状态重新初始化时,在 onStart() 之后调用此方法,此处在 savedInstanceState 中给出...

我认为这会有所帮助

【讨论】:

  • 您不能将 HaspMap 对象存储在 Bundles 中,AFAIK。
  • 我是 android 的初学者。如果你能给出实用的代码或示例,我可以很好地获取它......所以..请用代码详细说明它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多