Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

android - 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
    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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...