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

前端 未结 3 1552
孤独总比滥情好
孤独总比滥情好 2021-01-02 14:19
URI imageUri = null;

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


        
相关标签:
3条回答
  • 2021-01-02 15:05

    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();
    }
    
    0 讨论(0)
  • 2021-01-02 15:05

    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 讨论(0)
  • 2021-01-02 15:15

    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
    
    0 讨论(0)
提交回复
热议问题