开发者

How to store hashmap so that it can be retained it value after a device reboot?

开发者 https://www.devze.com 2023-02-09 09:56 出处:网络
I want to store the hashmap object in global class so that it will store value even 开发者_如何转开发after the mobile restart. Any idea how to go about this concept.serialize your hashmap object befor

I want to store the hashmap object in global class so that it will store value even 开发者_如何转开发after the mobile restart. Any idea how to go about this concept.


serialize your hashmap object before restarting and deserialize it after restart...

here is sample code for serialization..

public void serializeMap(HashMap<String,String> hm) {
    try {
        FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
        ObjectOutputStream oStream = new ObjectOutputStream(fStream);

        oStream.writeObject(hm);        
        oStream.flush();
        oStream.close();

        Log.v("Serialization success", "Success");
    } catch (Exception e) {
        Log.v("IO Exception", e.getMessage());
    }
}   

you can similarly read it by deserializing it....
Thanks....


Thanks very much but same thing can be done using the shared Preferences technique. Below is the code to add data into shared preferences and check if already exists.

  SharedPreferences preferences = getSharedPreferences(
                PREF_FILE_NAME, MODE_PRIVATE);
        if (value.equals("")) {

            boolean storedPreference = preferences.contains(key);
            if (storedPreference) {
                SharedPreferences.Editor editor = preferences.edit();
                editor.remove(key); // value to store
                Log.d("KEY",key);
                editor.commit();
            }
        }else{

            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(key, value); // value to store
            Log.d("KEY",key);
            editor.commit();
        }

then we can access using the

SharedPreferences preferences = getSharedPreferences(
                PREF_FILE_NAME, MODE_PRIVATE);
        Map<String, String> map = (Map<String, String>) preferences.getAll();
        if(!map.isEmpty()){
            Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                 Map.Entry pairs = (Map.Entry)iterator.next();
                    pairs.getKey()+pairs.getValue();
                          //write code here
            }
        }


Serialize it and save it in shared preferences or in a file. Whether you can do this, of course, depends on the data types being mapped from and to. (This won't work, for instance, if you try to serialize a View.)

0

精彩评论

暂无评论...
验证码 换一张
取 消