Search code examples
androidsharedpreferencesimageurl

Shared preferences to String array


I would like to know how I would be able to able achieve getting the strings from my shared preferences(I have already set up), then outputting it to a String array so that my Image Fetcher will be able to read it(It has to be an array for it to read).

In one activity I am setting the shared preferences:

        case R.id.FavouriteWallpaper:

        SharedPreferences prefs;
        prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("imgUrl", mImageUrl);
        editor.commit();

    }
    return super.onOptionsItemSelected(item);
}

In another class I am getting the string from shared preferences:

            SharedPreferences prefs;
        prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        prefs.getString("imgUrl", null); //Output imgUrl to String Array somehow


 // I would like my image fetcher to read a string array that has been fetched from shared preferences. 

mImageFetcher.loadImage(Fragment3.imgUrl[position
                - mNumColumns], imageView);

        return imageView;
    }

Solution

  • You can not really save an array to SharedPrerences, but you can store all your urls in a string like CSV (comma separated values) and store it in sharePreferences. You can write a manager that will have 2 methods. One to transform your array to CSV and store and the second get the CSV and transform it to an array. The second method is to save the data like a JSONArray to do this you also need to write a manager that will have 2 methods also, one to transform your array to JSONArray and store it in Shared Preferences, and the second to transform the jsonArray into your array.