Is it possible to add an array or object to SharedPreferences on Android

前端 未结 11 1618
别跟我提以往
别跟我提以往 2020-11-22 11:27

I have an ArrayList of objects that have a name and an icon pointer and I want to save it in SharedPreferences. How can I do?

NOTE:

相关标签:
11条回答
  • 2020-11-22 11:44

    When I was bugged with this, I got the serializing solution where, you can serialize your string, But I came up with a hack as well.

    Read this only if you haven't read about serializing, else go down and read my hack

    In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))

    Entering data in Shared preference :

    the rest of the code on line 38 -

    Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)

    Coming to my Hack :-

    Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it. Coz adding and retrieving String is easy with shared preferences. If you are worried about splitting just look up "splitting a string in java".

    [Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]

    PS: I am new to android, so don't know if it is a good hack, so lemme know if you find better hacks.

    0 讨论(0)
  • 2020-11-22 11:46

    Regardless of the API level, Check String arrays and Object arrays in 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;  
    }  
    
    0 讨论(0)
  • 2020-11-22 11:46

    You can use putStringSet

    This allow you to save a HashSet in your preferences, just like this:

    Save

    Set<String> values;
    
    SharedPreferences sharedPref = 
        mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
    
    Editor editor = sharedPref.edit();
    
    editor.putStringSet("YOUR_KEY", values);
    editor.apply();
    

    Retrive

    SharedPreferences sharedPref = 
        mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
    
    Editor editor = sharedPref.edit();
    
    Set<String> newList = editor.getStringSet("YOUR_KEY", null);
    

    The putStringSet allow just a Set and this is an unordered list.

    0 讨论(0)
  • 2020-11-22 11:50

    To write,

    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(1);
    jsonArray.put(2);
    Editor editor = prefs.edit();
    editor.putString("key", jsonArray.toString());
    System.out.println(jsonArray.toString());
    editor.commit();
    

    To Read,

    try {
        JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
        for (int i = 0; i < jsonArray2.length(); i++) {
             Log.d("your JSON Array", jsonArray2.getInt(i)+"");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-11-22 11:56

    This is the shared preferences code i use successfully, Refer this link:

      public class MainActivity extends Activity {
    
    private static final int RESULT_SETTINGS = 1;
    Button button;
    public String a="dd";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
     button = (Button) findViewById(R.id.btnoptions);
    
    
    setContentView(R.layout.activity_main);
    
      // showUserSettings();
      }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.settings, menu);
    return true;
     }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    
    case R.id.menu_settings:
     Intent i = new Intent(this, UserSettingActivity.class);
     startActivityForResult(i, RESULT_SETTINGS);
     break;
    
     }
    
    return true;
    }
    
    @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data)     {
      super.onActivityResult(requestCode, resultCode, data);
    
     switch (requestCode) {
     case RESULT_SETTINGS:
     showUserSettings();
     break;
    
     } 
    
      }
    
      private void showUserSettings() {
     SharedPreferences sharedPrefs = PreferenceManager
    .getDefaultSharedPreferences(this);
    
     StringBuilder builder = new StringBuilder();
    
     builder.append("\n Pet: "
      + sharedPrefs.getString("prefpetname", "NULL"));
    
     builder.append("\n Address:"
     + sharedPrefs.getString("prefaddress","NULL" ));
    
     builder.append("\n Your name: "
     + sharedPrefs.getString("prefname", "NULL"));
    
     TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);
    
    
      settingsTextView.setText(builder.toString());
    
    
        }
    
       }
    

    HAPPY CODING!

    0 讨论(0)
  • 2020-11-22 12:00

    For writing:

     private <T> void storeData(String key, T data) {
        ByteArrayOutputStream serializedData = new ByteArrayOutputStream();
    
        try {
            ObjectOutputStream serializer = new ObjectOutputStream(serializedData);
            serializer.writeObject(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        SharedPreferences sharedPreferences = getSharedPreferences(TAG, 0);
        SharedPreferences.Editor edit = sharedPreferences.edit();
    
        edit.putString(key, Base64.encodeToString(serializedData.toByteArray(), Base64.DEFAULT));
        edit.commit();
    }
    

    For reading:

    private <T> T getStoredData(String key) {
        SharedPreferences sharedPreferences = getSharedPreferences(TAG, 0);
        String serializedData = sharedPreferences.getString(key, null);
        T storedData = null;
        try {
            ByteArrayInputStream input = new ByteArrayInputStream(Base64.decode(serializedData, Base64.DEFAULT));
            ObjectInputStream inputStream = new ObjectInputStream(input);
            storedData = (T)inputStream.readObject();
        } catch (IOException|ClassNotFoundException|java.lang.IllegalArgumentException e) {
            e.printStackTrace();
        }
    
        return storedData;
    }
    
    0 讨论(0)
提交回复
热议问题