如何使用SharedPreferences保存URI或任何存储?

yos*_*i24 6 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();
}
Run Code Online (Sandbox Code Playgroud)

我正在使用此代码将URL转换为URI.我怎样才能将imageUri保存到SharedPreferences,或者将其删除的内存不能删除onDestroy()?

我不想做SQLite数据库,因为当URL改变时URI会改变.我不想用掉未使用的URI的内存

Foa*_*Guy 12

要开始使用SharedPreferences进行存储,您需要在onCreate()中使用类似的内容:

SharedPreferences myPrefs = getSharedPreferences(myTag, 0);
SharedPreferences.Editor myPrefsEdit = myPrefs.edit();
Run Code Online (Sandbox Code Playgroud)

我认为你可以做这样的事情来存储它:

myPrefsEdit.putString("url", imageUri.toString());
myPrefsEdit.commit();
Run Code Online (Sandbox Code Playgroud)

然后这样的东西来检索:

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


Kal*_*Kal 9

您只需保存URI的字符串表示即可.

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

然后使用Uri解析方法来检索它.

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String imageUriString = settings.getString("imageURI", null);
Uri imageUri = Uri.parse(imageUriString); <-- parse
Run Code Online (Sandbox Code Playgroud)