2011-08-24 58 views
6
URI imageUri = null; 

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

我正在使用此代码将URL转换为URI。我怎么能将imageUri保存到SharedPreferences或者它不会被删除的内存onDestroy()?如何使用SharedPreferences保存URI或任何存储?

我不想做SQLite数据库,因为当URL的change.I不想使用了未使用的URI的

回答

9

开始使用存储SharedPreferences你需要有这样的事情在你的onCreate()开始:

SharedPreferences myPrefs = getSharedPreferences(myTag, 0); 
SharedPreferences.Editor myPrefsEdit = myPrefs.edit(); 

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

myPrefsEdit.putString("url", imageUri.toString()); 
myPrefsEdit.commit(); 

然后是这样的检索:

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

内存来保存的URI作为首选项,你首先需要将其转换为一个包含URI将改变字符串使用getPath()方法。然后你可以像这样保存它。

SharedPreferences pref = getSharedPreferences("whateveryouwant", MODE_PRIVATE); 
SharedPreferences.Editor prefEditor = userSettings.edit(); 
prefEditor.putString("key", uriString); 
prefEditor.commit(); 
5

您可以保存URI的字符串表示形式。

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

然后使用Uri parse方法来检索它。

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
String imageUriString = settings.getString("imageURI", null); 
Uri imageUri = Uri.parse(imageUriString); <-- parse 
+0

在他的示例代码中,他使用了具有.create(String)而不是.aprse(String)的java.net.URI对象,如android.net.Uri。在其他方面使用其中一种有好处吗? – FoamyGuy

+0

我实际上认为android.net.Uri是OP试图保存到共享偏好的东西。如果不是,你的答案肯定是正确的。 – Kal

+0

我认为他们都会工作,而且我从来没有遇到过任何其他理由 – FoamyGuy

相关问题