How to Store Hashmap to android so that it will be reuse when application restart using shared preferences?

后端 未结 5 1971
余生分开走
余生分开走 2020-12-30 06:38

I want to store hashmap to my android application that when restart ,it shows last saved values of hashmap.

HashMap HtKpi=new HashMap&l         


        
5条回答
  •  感动是毒
    2020-12-30 07:09

    using Raghav's I created a complete working example:

    public class AppCache {
    public static HashMap 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) pref.getAll();
        if(hashMap == null) {
            hashMap = new HashMap();
        }
    }
    
    public static void SaveSettings(Context context) {
        if(hashMap == null) {
            hashMap = new HashMap();
        }
    
        //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();
    }
    }
    

    Then in your onCreate load it:

    @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));
    }
    

    at any time anywhere in your app update settings:

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

    in your onDestroy save settings to cache:

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

提交回复
热议问题