How to properly use load array and save array methods?

后端 未结 1 1273
野性不改
野性不改 2021-01-26 07:12

I have the following code which is designed for the user to click on a button and when they click on the button, the particular string they are viewing is Favorited and stored s

相关标签:
1条回答
  • 2021-01-26 08:04

    loadArray function returns String[]. You might want to use it like:

    String [] arr = loadArray("favorites");  
    

    This array can be used later as you asked in 2nd part. Hope this helps.

    Update [Based on your comment]

    So, if you want to grab text in TextView and wish to add it in a List/String array:

    1) Try to get the String from TextView

    TextView display = (TextView)findViewById(R.id.display);
    String toSave = display.getText().toString();
    

    2) Get the existing list from SharedPreferences using `loadArray':

    String [] arr = loadArray("favorites");  
    

    3) Add the new String to it:

    ArrayList<String> arrList = new ArrayList<String>();
    
    for (int i=0; i<arr.length(); i++) {
         arrList.add(arr[i]); //add old values to arraylist
    }
    // add new string to it: 
    arrList.add(toSave);
    
    //Get back your array
    String [] array = arrList.toArray(new String[arrList.size()]); 
    

    4) Save it Again.

    saveArray(array, "favorites");
    
    0 讨论(0)
提交回复
热议问题