android saves ArrayList<Object> to Shared Preferences

Keywords: JSON encoding xml codec




Today, let's briefly talk about how to keep ArrayList < Object > to Shared Preferences.


I've talked about keeping ArrayList < String > to Shared Preferences before, but how to keep Shared Preferences if there are classes in the collection?


Find two codes on the Internet.


1. Transform list to json for saving.


1 First, serialize custom objects

public class CoordinateAlterSample implements Serializable {
    private double x;
    private double y;
    private String name;

    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public double getY() {
        return y;
    }
    public void setY(double y) {
        this.y = y;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}


Second, you can save the list to Shared Preferences by converting it to json

List<CoordinateAlterSample> alterSamples = new ArrayList<CoordinateAlterSample>();
SharedPreferences.Editor editor = getSharedPreferences("AlterSamplesList", MODE_PRIVATE).edit();
Gson gson = new Gson();
String json = gson.toJson(alterSamples);
Log.d(TAG, "saved json is "+ json);
editor.putString("alterSampleJson", json);
editor.commit();


The corresponding extraction operation is:

SharedPreferences preferences = getSharedPreferences("AlterSamplesList", MODE_PRIVATE);
String json = preferences.getString("alterSampleJson", null);
if (json != null)
{
    Gson gson = new Gson();
    Type type = new TypeToken<List<CoordinateAlterSample>>(){}.getType();
    List<CoordinateAlterSample> alterSamples = new ArrayList<CoordinateAlterSample>();
    alterSamples = gson.fromJson(json, type);
    for(int i = 0; i < alterSamples.size(); i++)
    {
        Log.d(TAG, alterSamples.get(i).getName()+":" + alterSamples.get(i).getX() + "," + alterSamples.get(i).getY());
    }
}


Gson's jar package is used here and you can download it yourself.



2. Convert the data into Base64 encoding, and then save the converted data in the form of strings in the XML file.

Need to use: commons-codec-1.4.jar

AddNewWord addWord=new AddNewWord();
          addWord.setWords(word.getWords());
          addWord.setWordClass(i);
          SharedPreferences mySharedPreferences=getSharedPreferences("new_word", Activity.MODE_WORLD_READABLE);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
          ObjectOutputStream oos=null;
          try {
           oos = new ObjectOutputStream(baos);
           oos.writeObject(addWord);
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
          // Place Product objects in OutputStream
          // Convert the Product object into a byte array and encode it in base64
          String newWord = new String(Base64.encodeBase64(baos.toByteArray()));
          SharedPreferences.Editor editor = mySharedPreferences.edit();
          // Write the encoding string to the base64.xml file
          editor.putString("newWord", newWord);
          editor.commit();
//Read object:
    String wordBase64 = mySharedPreferences.getString("new_word", "");
   // Decoding Base64 format strings
       byte[] base64Bytes = Base64.decodeBase64(wordBase64 .getBytes());
         ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
      ObjectInputStream ois = new ObjectInputStream(bais);
  // Reading Product Objects from ObjectInputStream
     AddNewWord addWord= (AddNewWord ) ois.readObject();
//Object entities:

public class AddNewWord implements Serializable{

 private static final long serialVersionUID = -37782648386953312L;
 private String words;
 private int wordClass;
 public String getWords() {
  return words;
 }
 public void setWords(String words) {
  this.words = words;
 }
 public int getWordClass() {
  return wordClass;
 }
 public void setWordClass(int wordClass) {
  this.wordClass = wordClass;
 }
 @Override
 public String toString() {
  return "AddNewWord [words=" + words
    + ", wordClass=" + wordClass
    + "]";
 }

}


In this way, as in List < String >, the list data is stored in a certain order and then read in the same order. See my blog about storing list < String > specifically.


android saves ArrayList < Object > until Shared Preferences.


It's that simple.



Posted by mahdi_20 on Wed, 13 Feb 2019 10:24:18 -0800