【问题标题】:How to save HashMap in XML file and getting it back in android?如何将 HashMap 保存在 XML 文件中并将其取回 android?
【发布时间】:2012-03-22 10:47:50
【问题描述】:

我有一个 HashMap,其中包含一些键值格式(字符串、对象)的数据。我想将该哈希图以 XML 格式文件保存在 android 手机内存中,然后像在 Map 中一样再次检索它。如何在android中实现这一点。

提前致谢

【问题讨论】:

    标签: android xml file hashmap


    【解决方案1】:

    这里是代码

        import java.io.FileInputStream;
        import java.io.FileOutputStream;
        import java.io.ObjectInputStream;
        import java.io.ObjectOutputStream;
    
        import java.util.Arrays;
        import java.util.List;
    
        public class MainClass {
          public static void main(String[] a) throws Exception {
    
            List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
            FileOutputStream fos = new FileOutputStream("list.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(list);
            oos.close();
    
            FileInputStream fis = new FileInputStream("list.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            List anotherList = (List) ois.readObject();
            ois.close();
    
    
          }
        }
    

    【讨论】:

      【解决方案2】:

      我不知道这是否能解决您的问题,但您是否使用 sharedPreferences 检查过? 它使您可以保存键值,而无需负责创建文件并从中检索。 它易于创建、插入和读取

      在这里查看
      http://developer.android.com/reference/android/content/SharedPreferences.html

      //create - open the sharedPreferences file
      SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
      
      //get an editor
      SharedPreferences.Editor prefsEditor = myPrefs.edit();
      
      //add key-value
      prefsEditor.putString("MY_KEY", "MY_VALUE");
      //commit 
      prefsEditor.commit();
      
      //get the value from key (the second param is the default if the value is null )
      pref.getString("MY_KEY","VALUE_IF_NULL");
      

      【讨论】:

      • 非常感谢您的回答。但是,如果您给我一些示例代码,那么它对我会更有帮助。可以吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      相关资源
      最近更新 更多