开发者

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

开发者 https://www.devze.com 2023-03-30 12:12 出处:网络
URI imageUri = null; //Setting the Uri of aURL to imageUri. try { imageUri = aURL.toURI(); } catch (URISyntaxException e1) {
URI imageUri = null;

//Setting the Uri of aURL to imageUri.
try {
    imageUri = aURL.toURI();
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch 开发者_如何学Cblock
    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


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


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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消