Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Storing and retrieving String[ ] Array using SharedPreferences in Android.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 7.44k
    Comment on it

    I came across to the many questions asking about to store some kind data in Shared-preferences such as String[] array. Many of these questions are answered with "Use a database".

    But here i will show you a perfect piece of code by which you can store and retrieve an String[] array in Shared-preferences.

    You can put these two methods in your utility class and call than from the class where you want to store and retrieve data.

    This is the method to save your String[] array in Shared-preferences.

     public boolean saveArrayData(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();
    
      }
    

    Now to get the array back, you just have to call the getArrayData.

      public String[] getArrayData(String arrayName, Context mContext) {
             SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
               int size = prefs.getInt(arrayName + "_ ", 0);
                   for(int i=0 ; i<array.length ; i++){
                         editor.getString(arrayName + "_ " + i, array[i]);
                   }
                return editor.commit();
    

    }

    This is the whole process of storing and retrieving String[] array by using Shared-preferences. Hope you like it...

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: