0

I was struck up with an issue, I would like to save the linkedhashmap variables in the shared preferences and my code is here..

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 i.e reqVariables when wifi is not available because globalappvariables will be available only when net is available i.e from

    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.

kumar Sudheer
  • 705
  • 3
  • 8
  • 28
  • You can only save primitive data-types like `int`, `float` etc in SharedPreferences. Have a look at http://stackoverflow.com/questions/7944601/saving-a-hash-map-into-shared-preferences – Braj May 15 '14 at 07:16

4 Answers4

0

You can not save a HashMap in to SharedPrefernces in android. So i think you can do this via a trick,example: you will save all keys of hashmap as String[] & all value as String[]

tauitdnmd
  • 369
  • 2
  • 9
0

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.

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;  
}
Ahad Porkar
  • 1,666
  • 2
  • 33
  • 68
  • I didn't get about here, get array from ur list : Foo[] array = list.toArray(new Foo[list.size()]); what is Foo[] and list represents overe here.. – kumar Sudheer May 15 '14 at 07:35
  • if u want to use "saveArray" function u should pass array as parameter. so i convert list to array. the line :Foo[] array = list.toArray(new Foo[list.size()]); ive changed for more simplicity , check edit now. – Ahad Porkar May 15 '14 at 07:46
0
// 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],""));
        }
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
0

If you don't want to code a lot, then just download 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);
}
kupsef
  • 3,357
  • 1
  • 21
  • 31