简体   繁体   English

将LinkedHashMap变量保存到android中的共享首选项中

[英]Save the LinkedHashMap variables in to shared preferences in android

I was struck up with an issue, I would like to save the linkedhashmap variables in the shared preferences and my code is here.. 我被一个问题困扰,我想将linkedhashmap变量保存在共享首选项中,我的代码在这里。

public static LinkedHashMap<String, AppVariable> GlobalAppVariables;

if (Constants.DEVICE_ID == 0) {
String accounts_service = serverSync.getCentralServer(this,serial_number);
   if (accounts_service != null){
        Constants.MACHINE_CENTRAL_SERVER = accounts_service;
        }
       Constants.REGISTER_DEVICE_SERVICE = String.format("%sCommon/RegisterMachine", Constants.MACHINE_CENTRAL_SERVER); 
       GlobalAppVariables = serverSync.registerDevice(this, serial_number);       
} 

        SharedPreferences sharedPref= getSharedPreferences("mypref", 0);    
    SharedPreferences.Editor editor= sharedPref.edit();
    editor.putString("name", GlobalAppVariables.toString());
    editor.commit();     

    SharedPreferences sharedPref1= getSharedPreferences("mypref", 0);
    LinkedHashMap<String, AppVariable> reqVariables= sharedPref1.getString("name", "");

Now my issue is I would like to save the globalappvariables in shared preferences and use the same variables ie reqVariables when wifi is not available because globalappvariables will be available only when net is available ie from 现在我的问题是我想将globalappvariables保存在共享首选项中,并在wifi不可用时使用相同的变量,即reqVariables,因为globalappvariables仅在net可用时才可用,即从

    GlobalAppVariables = serverSync.registerDevice(this, serial_number);    

When I build the code like above, i am getting the issue 当我像上面那样构建代码时,我遇到了问题

The method putString(String, String) in the type SharedPreferences.Editor is not applicable for the arguments (String, LinkedHashMap<String,AppVariable>)   

So please suggest me how to save the appvariables. 因此,请建议我如何保存这些变量。 Hoping the issue is understandable . 希望这个问题是可以理解的。 Thanks in advance. 提前致谢。

You can not save a HashMap in to SharedPrefernces in android. 您无法将HashMap保存到android中的SharedPrefernces中。 So i think you can do this via a trick,example: you will save all keys of hashmap as String[] & all value as String[] 因此,我想您可以通过一个技巧来做到这一点,例如:您将把hashmap的所有键保存为String []并将所有值保存为String []

Put ur map into list : 将您的地图放入清单:

for example : 例如 :

LinkedHashMap < String, String > map
List < String > keyList;
List < String > valueList;

map.keySet();
map.values();
List<String> keyList = new ArrayList<String>(map.keySet());
List<String> valueList = new ArrayList<String>(map.values());

get array from ur list : 从您的列表中获取数组:

 String[] MyArr = new String[My_list.size()];
 MyArr = My_list.toArray(MyArr);

and then save array into ur sharedpreferences. 然后将数组保存到您的sharedpreferences中。

Save Array: 保存数组:

public boolean saveArray(String[] array, String arrayName, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i=0;i<array.length;i++)  
        editor.putString(arrayName + "_" + i, array[i]);  
    return editor.commit();  
} 

Load array : 加载数组:

public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}
// Try this way,hope this will help you to solve your problem...

        HashMap<String,String> map = new HashMap<String, String>();
        map.put("name","ANC");
        map.put("address","XYZ");
        map.put("age","20");
        map.put("phone","123456");


        // Set SharedPreferences
        SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
        String keys="";
        Iterator<String> itr = map.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            SharedPreferences.Editor editor= sharedPref.edit();
            editor.putString(key,map.get(key));
            editor.commit();
            keys += itr.next()+",";
        }
        keys = keys.substring(0,keys.length()-1);
        SharedPreferences.Editor editor= sharedPref.edit();
        editor.putString("keys",keys);
        editor.commit();

        // Get SharedPreferences
        SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
        String[] keysArray = sharedPref.getString("keys","").split(",");
        for (int i=0;i<keysArray.length;i++){
            System.out.println("Key : "+keysArray[i]+" Value : "+sharedPref.getString(keysArray[i],""));
        }

If you don't want to code a lot, then just download Gson . 如果您不想编写太多代码,请下载Gson Here is the sketch: 这是草图:

private Type entityType = new TypeToken<LinkedHashMap<String, AppVariable>>(){}.getType();

private void save(LinkedHashMap<String, AppVariable> map){
    Gson gson = new Gson();
    String data = gson.toJson(map, entityType);

    getSharedPreferences("mypref", 0)
    .edit()
    .putString("name", data)
    .commit();
}

private LinkedHashMap<String, AppVariable> load(){
    Gson gson = new Gson();
    String data = getSharedPreferences("mypref", 0).getString("name", "");

    return gson.fromJson(data, entityType);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM