Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, January 23, 2016

Save ArrayList to SharedPreferences

Save ArrayList to SharedPreferences


I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?

Answer by MByD for Save ArrayList to SharedPreferences


You can convert it to JSON String and store the string in the shared preferences.

Answer by evilone for Save ArrayList to SharedPreferences


After API 11 the SharedPreferences Editor accept Sets. You could convert your List into a HashSet or something similar and store it like that. When your read it back, convert it into an ArrayList, sort it if needed and you're good to go.

//Retrieve the values  Set set = myScores.getStringSet("key", null);    //Set the values  Set set = new HashSet();  set.addAll(listOfExistingScores);  scoreEditor.putStringSet("key", set);  scoreEditor.commit();  

You can also serialize your ArrayList and then save/read it to/from SharedPreferences. Below is the solution:

EDIT: Ok, below is the solution to save ArrayList as serialized object to SharedPreferences and then read it from SharedPreferences.

Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, its simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into string.

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method:

public void addTask(Task t) {          if (null == currentTasks) {              currentTasks = new ArrayList();          }          currentTasks.add(t);            //save the task list to preference          SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);          Editor editor = prefs.edit();          try {              editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));          } catch (IOException e) {              e.printStackTrace();          }          editor.commit();      }  

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method:

public void onCreate() {          super.onCreate();          if (null == currentTasks) {              currentTasks = new ArrayList();          }            //      load tasks from preference          SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);            try {              currentTasks = (ArrayList) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList())));          } catch (IOException e) {              e.printStackTrace();          } catch (ClassNotFoundException e) {              e.printStackTrace();          }      }  

You can get ObjectSerializer class from Apache Pig project ObjectSerializer.java

Answer by Phil for Save ArrayList to SharedPreferences


You can convert it to a Map Object to store it, then change the values back to an ArrayList when you retrieve the SharedPreferences.

Answer by Carlos Silva for Save ArrayList to SharedPreferences


Why don't you stick your arraylist on an Application class? It only get's destroyed when the app is really killed, so, it will stick around for as long as the app is available.

Answer by Preet for Save ArrayList to SharedPreferences


Saving Array in Shared Preferences

public static boolean saveArray()  {      SharedPreferences sp = SharedPreferences.getDefaultSharedPreferences(this);      SharedPreferences.Editor mEdit1 = sp.edit();      mEdit1.putInt("Status_size", sKey.size()); /* sKey is an array */         for(int i=0;i

Loading Array Data from Shared Preferences

public static void loadArray(Context mContext)  {        Shared Preferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);      sKey.clear();      int size = mSharedPreference1.getInt("Status_size", 0);          for(int i=0;i

Answer by Emerald214 for Save ArrayList to SharedPreferences


You could refer the serializeKey() and deserializeKey() functions from FacebookSDK's SharedPreferencesTokenCache class. It converts the supportedType into the JSON object and store the JSON string into SharedPreferences. You could download SDK from here

private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor)      throws JSONException {      Object value = bundle.get(key);      if (value == null) {          // Cannot serialize null values.          return;      }        String supportedType = null;      JSONArray jsonArray = null;      JSONObject json = new JSONObject();        if (value instanceof Byte) {          supportedType = TYPE_BYTE;          json.put(JSON_VALUE, ((Byte)value).intValue());      } else if (value instanceof Short) {          supportedType = TYPE_SHORT;          json.put(JSON_VALUE, ((Short)value).intValue());      } else if (value instanceof Integer) {          supportedType = TYPE_INTEGER;          json.put(JSON_VALUE, ((Integer)value).intValue());      } else if (value instanceof Long) {          supportedType = TYPE_LONG;          json.put(JSON_VALUE, ((Long)value).longValue());      } else if (value instanceof Float) {          supportedType = TYPE_FLOAT;          json.put(JSON_VALUE, ((Float)value).doubleValue());      } else if (value instanceof Double) {          supportedType = TYPE_DOUBLE;          json.put(JSON_VALUE, ((Double)value).doubleValue());      } else if (value instanceof Boolean) {          supportedType = TYPE_BOOLEAN;          json.put(JSON_VALUE, ((Boolean)value).booleanValue());      } else if (value instanceof Character) {          supportedType = TYPE_CHAR;          json.put(JSON_VALUE, value.toString());      } else if (value instanceof String) {          supportedType = TYPE_STRING;          json.put(JSON_VALUE, (String)value);      } else {          // Optimistically create a JSONArray. If not an array type, we can null          // it out later          jsonArray = new JSONArray();          if (value instanceof byte[]) {              supportedType = TYPE_BYTE_ARRAY;              for (byte v : (byte[])value) {                  jsonArray.put((int)v);              }          } else if (value instanceof short[]) {              supportedType = TYPE_SHORT_ARRAY;              for (short v : (short[])value) {                  jsonArray.put((int)v);              }          } else if (value instanceof int[]) {              supportedType = TYPE_INTEGER_ARRAY;              for (int v : (int[])value) {                  jsonArray.put(v);              }          } else if (value instanceof long[]) {              supportedType = TYPE_LONG_ARRAY;              for (long v : (long[])value) {                  jsonArray.put(v);              }          } else if (value instanceof float[]) {              supportedType = TYPE_FLOAT_ARRAY;              for (float v : (float[])value) {                  jsonArray.put((double)v);              }          } else if (value instanceof double[]) {              supportedType = TYPE_DOUBLE_ARRAY;              for (double v : (double[])value) {                  jsonArray.put(v);              }          } else if (value instanceof boolean[]) {              supportedType = TYPE_BOOLEAN_ARRAY;              for (boolean v : (boolean[])value) {                  jsonArray.put(v);              }          } else if (value instanceof char[]) {              supportedType = TYPE_CHAR_ARRAY;              for (char v : (char[])value) {                  jsonArray.put(String.valueOf(v));              }          } else if (value instanceof List) {              supportedType = TYPE_STRING_LIST;              @SuppressWarnings("unchecked")              List stringList = (List)value;              for (String v : stringList) {                  jsonArray.put((v == null) ? JSONObject.NULL : v);              }          } else {              // Unsupported type. Clear out the array as a precaution even though              // it is redundant with the null supportedType.              jsonArray = null;          }      }        if (supportedType != null) {          json.put(JSON_VALUE_TYPE, supportedType);          if (jsonArray != null) {              // If we have an array, it has already been converted to JSON. So use              // that instead.              json.putOpt(JSON_VALUE, jsonArray);          }            String jsonString = json.toString();          editor.putString(key, jsonString);      }  }    private void deserializeKey(String key, Bundle bundle)          throws JSONException {      String jsonString = cache.getString(key, "{}");      JSONObject json = new JSONObject(jsonString);        String valueType = json.getString(JSON_VALUE_TYPE);        if (valueType.equals(TYPE_BOOLEAN)) {          bundle.putBoolean(key, json.getBoolean(JSON_VALUE));      } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          boolean[] array = new boolean[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = jsonArray.getBoolean(i);          }          bundle.putBooleanArray(key, array);      } else if (valueType.equals(TYPE_BYTE)) {          bundle.putByte(key, (byte)json.getInt(JSON_VALUE));      } else if (valueType.equals(TYPE_BYTE_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          byte[] array = new byte[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = (byte)jsonArray.getInt(i);          }          bundle.putByteArray(key, array);      } else if (valueType.equals(TYPE_SHORT)) {          bundle.putShort(key, (short)json.getInt(JSON_VALUE));      } else if (valueType.equals(TYPE_SHORT_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          short[] array = new short[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = (short)jsonArray.getInt(i);          }          bundle.putShortArray(key, array);      } else if (valueType.equals(TYPE_INTEGER)) {          bundle.putInt(key, json.getInt(JSON_VALUE));      } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          int[] array = new int[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = jsonArray.getInt(i);          }          bundle.putIntArray(key, array);      } else if (valueType.equals(TYPE_LONG)) {          bundle.putLong(key, json.getLong(JSON_VALUE));      } else if (valueType.equals(TYPE_LONG_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          long[] array = new long[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = jsonArray.getLong(i);          }          bundle.putLongArray(key, array);      } else if (valueType.equals(TYPE_FLOAT)) {          bundle.putFloat(key, (float)json.getDouble(JSON_VALUE));      } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          float[] array = new float[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = (float)jsonArray.getDouble(i);          }          bundle.putFloatArray(key, array);      } else if (valueType.equals(TYPE_DOUBLE)) {          bundle.putDouble(key, json.getDouble(JSON_VALUE));      } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          double[] array = new double[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              array[i] = jsonArray.getDouble(i);          }          bundle.putDoubleArray(key, array);      } else if (valueType.equals(TYPE_CHAR)) {          String charString = json.getString(JSON_VALUE);          if (charString != null && charString.length() == 1) {              bundle.putChar(key, charString.charAt(0));          }      } else if (valueType.equals(TYPE_CHAR_ARRAY)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          char[] array = new char[jsonArray.length()];          for (int i = 0; i < array.length; i++) {              String charString = jsonArray.getString(i);              if (charString != null && charString.length() == 1) {                  array[i] = charString.charAt(0);              }          }          bundle.putCharArray(key, array);      } else if (valueType.equals(TYPE_STRING)) {          bundle.putString(key, json.getString(JSON_VALUE));      } else if (valueType.equals(TYPE_STRING_LIST)) {          JSONArray jsonArray = json.getJSONArray(JSON_VALUE);          int numStrings = jsonArray.length();          ArrayList stringList = new ArrayList(numStrings);          for (int i = 0; i < numStrings; i++) {              Object jsonStringValue = jsonArray.get(i);              stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String)jsonStringValue);          }          bundle.putStringArrayList(key, stringList);      }  }  

Answer by Winston Smith for Save ArrayList to SharedPreferences


best way is that convert to JSOn string using GSON and save this string to SharedPreference. I also use this way to cache responses.

Answer by Anshul Bansal for Save ArrayList to SharedPreferences


The best way i have been able to find is a make a 2D Array of keys and put the custom items of the array in the 2-D array of keys and then retrieve it through the 2D arra on startup. I did not like the idea of using string set because most of the android users are still on Gingerbread and using string set requires honeycomb.

Sample Code: here ditor is the shared pref editor and rowitem is my custom object.

editor.putString(genrealfeedkey[j][1], Rowitemslist.get(j).getname());          editor.putString(genrealfeedkey[j][2], Rowitemslist.get(j).getdescription());          editor.putString(genrealfeedkey[j][3], Rowitemslist.get(j).getlink());          editor.putString(genrealfeedkey[j][4], Rowitemslist.get(j).getid());          editor.putString(genrealfeedkey[j][5], Rowitemslist.get(j).getmessage());  

Answer by kc ochibili for Save ArrayList to SharedPreferences


Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.

TinyDB tinydb = new TinyDB(context);  

to put

tinydb.putList("MyUsers", mUsersArray);  

to get

tinydb.getList("MyUsers");  

Answer by SKT for Save ArrayList to SharedPreferences


You can also convert the arraylist into a String and save that in preference

private String convertToString(ArrayList list) {                StringBuilder sb = new StringBuilder();              String delim = "";              for (String s : list)              {                  sb.append(delim);                  sb.append(s);;                  delim = ",";              }              return sb.toString();          }    private ArrayList convertToArray(String string) {                ArrayList list = new ArrayList(Arrays.asList(string.split(",")));              return list;          }  

You can save the Arraylist after converting it to string using convertToString method and retrieve the string and convert it to array using convertToArray

After API 11 you can save set directly to SharedPreferences though !!! :)

Answer by nirav kalola for Save ArrayList to SharedPreferences


i got complete solution to store arraylist in sharedpreferences and retrive in any activity when you want

check this: http://www.nkdroid.com/2014/11/arraylist-in-sharedpreference.html

Answer by Ayman Al-Absi for Save ArrayList to SharedPreferences


As @nirav said, best solution is store it in sharedPrefernces as a json text by using Gson utility class. Below sample code:

//Retrieve the values  Gson gson = new Gson();  String jsonText = Prefs.getString("key", null);  String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson      //Set the values  Gson gson = new Gson();  List textList = new ArrayList();  textList.addAll(data);  String jsonText = gson.toJson(textList);  prefsEditor.putString("key", jsonText);  prefsEditor.commit();  

Answer by tmr for Save ArrayList to SharedPreferences


following code is the accepted answer, with a few more lines for new folks (me), eg. shows how to convert the set type object back to arrayList, and additional guidance on what goes before '.putStringSet' and '.getStringSet'. (thank you evilone)

// shared preferences     private SharedPreferences preferences;     private SharedPreferences.Editor nsuserdefaults;    // setup persistent data          preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);          nsuserdefaults = preferences.edit();            arrayOfMemberUrlsUserIsFollowing = new ArrayList();          //Retrieve followers from sharedPreferences          Set set = preferences.getStringSet("following", null);            if (set == null) {              // lazy instantiate array              arrayOfMemberUrlsUserIsFollowing = new ArrayList();          } else {              // there is data from previous run              arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);          }    // convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults                  Set set = new HashSet();                  set.addAll(arrayOfMemberUrlsUserIsFollowing);                  nsuserdefaults.putStringSet("following", set);                  nsuserdefaults.commit();  

Answer by user4680583 for Save ArrayList to SharedPreferences


    public  void saveUserName(Context con,String username)      {          try          {              usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);              usernameEditor = usernameSharedPreferences.edit();              usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1));               int size=USERNAME.size();//USERNAME is arrayList              usernameEditor.putString(PREFS_KEY_USERNAME+size,username);              usernameEditor.commit();          }          catch(Exception e)          {              e.printStackTrace();          }        }      public void loadUserName(Context con)      {            try          {              usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);              size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);              USERNAME.clear();              for(int i=0;i(this, android.R.layout.simple_dropdown_item_1line, USERNAME);              username.setAdapter(usernameArrayAdapter);              username.setThreshold(0);            }          catch(Exception e)          {              e.printStackTrace();          }      }  

Answer by Atul O Holic for Save ArrayList to SharedPreferences


All of the above answers are correct. :) I myself used one of these for my situation. However when I read the question I found that the OP is actually talking about a different scenario than the title of this post, if I didn't get it wrong.

"I need the array to stick around even if the user leaves the activity and then wants to come back at a later time"

He actually wants the data to be stored till the app is open, irrespective of user changing screens within the application.

"however I don't need the array available after the application has been closed completely"

But once the application is closed data should not be preserved.Hence I feel using SharedPreferences is not the optimal way for this.

What one can do for this requirement is create a class which extends Application class.

public class MyApp extends Application {        //Pardon me for using global ;)        private ArrayList globalArray;        public void setGlobalArrayOfCustomObjects(ArrayList newArray){          globalArray = newArray;       }        public ArrayList getGlobalArrayOfCustomObjects(){          return globalArray;      }    }  

Using the setter and getter the ArrayList can be accessed from anywhere withing the Application. And the best part is once the app is closed, we do not have to worry about the data being stored. :)

Answer by Maulik Gohel for Save ArrayList to SharedPreferences


//Set the values  intent.putParcelableArrayListExtra("key",collection);    //Retrieve the values  ArrayList onlineMembers = data.getParcelableArrayListExtra("key");  

Answer by Ratanachai S. for Save ArrayList to SharedPreferences


It's very simple using getStringSet and putStringSet in SharedPreferences, but in my case, I have to duplicate the Set object before I can add anything to the Set. Or else, the Set will not be saved if my app is force closed. Probably because of the note below in the API below. (It saved though if app is closed by back button).

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all. http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());  SharedPreferences.Editor editor = prefs.edit();    Set outSet = prefs.getStringSet("key", new HashSet());  Set workingSet = new HashSet(outSet);  workingSet.add("Another String");    editor.putStringSet("key", workingSet);  editor.commit();  

Answer by Manuel Schmitzberger for Save ArrayList to SharedPreferences


don't forget to implement Serializable:

Class dataBean implements Serializable{   public String name;  }  ArrayList dataBeanArrayList = new ArrayList();  

http://stackoverflow.com/a/7635154/4639974


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.