yoshi24 yoshi24 - 3 months ago 34
Android Question

How to use SharedPreferences to save a URI, or any Storage?

URI imageUri = null;

//Setting the Uri of aURL to imageUri.
try {
imageUri = aURL.toURI();
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block

I am using this code to translate a URL to a URI. How could I save the imageUri to a SharedPreferences, or a memory where it wouldnt be deleted onDestroy()?

I dont want to do SQLite database because the URI will change when the URL's change.I dont want to use up memory for unused URI's


To get started using SharedPreferences for storage you'll need to have something like this in your onCreate():

    SharedPreferences myPrefs = getSharedPreferences(myTag, 0);
    SharedPreferences.Editor myPrefsEdit = myPrefs.edit();

I think you can do something like this to store it:

    myPrefsEdit.putString("url", imageUri.toString());

And then something like this to retrieve:

    try {
        imageUri = URI.create(myPrefs.getString("url", "defaultString"));
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block

edit: URI.create() would have probably been better than using the string constructor to make your URI object.