15
URI imageUri = null;

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

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

Terry
  • 14,529
  • 13
  • 63
  • 88
yoshi24
  • 3,147
  • 8
  • 45
  • 62

3 Answers3

26

You can just save a string representation of your URI.

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("imageURI", imageUri.toString()); <-- toString()

Then use the Uri parse method to retrieve it.

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String imageUriString = settings.getString("imageURI", null);
Uri imageUri = Uri.parse(imageUriString); <-- parse
Daniele
  • 4,163
  • 7
  • 44
  • 95
Kal
  • 24,724
  • 7
  • 65
  • 65
  • In his example code he used the java.net.URI object which has .create(String) instead of .parse(String) like the android.net.Uri. Is there an upside to using one of these over the other? – FoamyGuy Aug 24 '11 at 02:05
  • I actually assumed android.net.Uri was what the OP was trying to save to shared preferences. If not, your answer is definitely the correct one. – Kal Aug 24 '11 at 02:12
  • I think they would both work, and I have never come across any any reasons for one over the other – FoamyGuy Aug 24 '11 at 02:52
18

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());
myPrefsEdit.commit();

And then something like this to retrieve:

try {
    imageUri = URI.create(myPrefs.getString("url", "defaultString"));
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
stkent
  • 19,772
  • 14
  • 85
  • 111
FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
0

To save the uri as a preference you first need to translate it to a string using the getPath() method. Then you can store it like this.

SharedPreferences pref = getSharedPreferences("whateveryouwant", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = userSettings.edit();  
prefEditor.putString("key", uriString);  
prefEditor.commit();
NSjonas
  • 10,693
  • 9
  • 66
  • 92