Question

i am developing an android app where i have to save dates (* as given in array)
i am doing this by using shared preferences 
my code is working fine but it do some different behaviour which i dont know why
  a.> when i am saving array in shared prefrences it works perfect as i want but 
  b.> when it comes to fetching data it keeps single date  if the date occurs twice in      array ex.. 24 occurs 2 times in my array but on fetching it show me single 24
  c.> also it gives me unordered representation of array 

 i dont know why this is happening and how to solve it 
 **some one told me to use serialize but i dont know how to do this? **    
    String[][] my_date;
    my_date = new String[][] {
                {"14","26"},
                {"12","16","24","27"},
                {"17"},
                {"8","13","18"},
                {"14"},
                {},
                {"29"},
                {"15","18"},
                {},
                {"2","3","6","8","23"},
                {"4","6","24"},
                {}
        };

    /* storing the data in shared preferences */
        SharedPreferences pref = arg0.getSharedPreferences("MyPref", 0); // 0 - for private mode
        SharedPreferences.Editor editor = pref.edit();

            Set<String> set = new HashSet<String>();
               for(int i=0; i<my_date.length;i++){
                   for(int j =0; j<my_date[i].length;j++){
                       set.add("'"+my_date[i][j]+"'"); 
                       Log.v("dates",my_date[i][j]);
                   }
               }
               editor.putStringSet("dates", set);
               editor.commit();

/* fetching saved data */
     set=pref.getStringSet("dates", set);
     Log.v("dates",set+"----"+set.size());  
Was it helpful?

Solution

First of all: This is a kind of a bad idea. You'd probably rather want to store things in a way so that you can make partial edits of them, eg. like using your own custom SQLLite database.

But if you're fine with the hacky approach, and you want to store that multi-dimension array in shared preferences, you could probably just serialize it to a string and store the string in the shared prefs.

You might just borrow pieces from this example of how to serialize a thing to a string: Reliably convert any object to String and then back again

And then take that string and store it in the shared prefs.

Edit: Oh well, I was curious so I tried it out.. I actually found I had to base64 encode the string as well, and I wish I could explain why in a cohesive manner, but this is roughly what I did:

private void mySharedPreferencesThing() {
    String[][] before = new String[][] {{"1","2","3"}, {}, {"4","5","6"}};

    System.out.println("String thing before: " + arrayToString(before));

    SharedPreferences sp = getSharedPreferences("lolcats", MODE_PRIVATE);
    String[][] after = null;
    try {
        sp.edit().putString("cats", twoDimensionalStringArrayToString(before)).commit();
        after = stringToTwoDimensionalStringArray(sp.getString("cats", null));
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("String thing after: " + arrayToString(after));
}

// Just for debugging and knowing that it looks correct - there may be
// something built in to do this
private String arrayToString(String[][] arr) {
    StringBuilder sb = new StringBuilder();
    sb.append("{\n");
    for (int i = 0; i < arr.length; i++) {
        sb.append("\t{" + TextUtils.join(", ", arr[i]) + "}");
        if (i != arr.length - 1) { sb.append(","); }
        sb.append("\n");
    }
    sb.append("}");
    return sb.toString();
}

private String twoDimensionalStringArrayToString(String[][] s) throws UnsupportedEncodingException, IOException {
    ByteArrayOutputStream bo = null;
    ObjectOutputStream so = null;
    Base64OutputStream b64 = null;
    try {
        bo = new ByteArrayOutputStream();
        b64 = new Base64OutputStream(bo, Base64.DEFAULT);
        so = new ObjectOutputStream(b64);
        so.writeObject(s);
        return bo.toString("UTF-8");
    } finally {
        if (bo != null) { bo.close(); }
        if (b64 != null) { b64.close(); }
        if (so != null) { so.close(); }
    }
}

private String[][] stringToTwoDimensionalStringArray(String s) throws ClassNotFoundException, IOException {
    ByteArrayInputStream bi = null;
    ObjectInputStream si = null;
    Base64InputStream b64 = null;
    try {
        byte b[] = s.getBytes("UTF-8"); 
        bi = new ByteArrayInputStream(b);
        b64 = new Base64InputStream(bi, Base64.DEFAULT);
        si = new ObjectInputStream(b64);
        return (String[][]) si.readObject();
    } finally {
        if (bi != null) { bi.close(); }
        if (b64 != null) { b64.close(); }
        if (si != null) { si.close(); }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top