Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 536
yoshi24 Avatar asked Aug 24 '11 01:08

yoshi24


People also ask

Can SharedPreferences store objects?

We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference. Note : Remember to add compile 'com.

What is the method used to store and retrieve data on the SharedPreferences?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

What can I store in shared preferences?

Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.


2 Answers

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
like image 106
Kal Avatar answered Oct 21 '22 21:10

Kal


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();
}
like image 35
FoamyGuy Avatar answered Oct 21 '22 21:10

FoamyGuy