Skip to content Skip to sidebar Skip to footer

How To Store Hashmap So That It Can Be Retained It Value After A Device Reboot?

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.

Solution 1:

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

here is sample code for serialization..

publicvoidserializeMap(HashMap<String,String> hm) {
    try {
        FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
        ObjectOutputStream oStream = newObjectOutputStream(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....

Solution 2:

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.

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

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

            SharedPreferences.Editoreditor= 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
            }
        }

Solution 3:

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.)

Post a Comment for "How To Store Hashmap So That It Can Be Retained It Value After A Device Reboot?"