【问题标题】:Enter an URL and store with shared preference Android输入 URL 并使用共享偏好 Android 存储
【发布时间】:2014-12-17 05:40:34
【问题描述】:

我希望用户在我的 SettingsActivity 中输入其 URL,并将该变量保存以供在另一个 Activity(例如 Main)中重复使用,并将其显示在 webview 中(通过添加,例如:http://myURL/example1),我知道我需要使用共享偏好,但我不知道如何,你能给我一个代码吗?

【问题讨论】:

    标签: android sharedpreferences store


    【解决方案1】:

    存储:

    public static final String PREFS_NAME = "MyAppSharedPrefs";
    
                 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                 SharedPreferences.Editor editor = settings.edit();
                 editor.putString("UsersUrl", URL HERE);
                 editor.commit();
    

    然后获取网址:

     public static final String PREFS_NAME = "MyAppSharedPrefs";
    
     SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
     String setting = settings.getString("UsersUrl", def);
    

    注意:您可以将 MyAappSharedPrefs 设置为任何您想要的,它只是确定您要保存到哪个共享首选项文件。 您也可以使用 UsersUrl,它只是一个变量名。 说如果你设置为:MyUrl,你在检索设置的时候也必须写MyUrl。

    【讨论】:

      【解决方案2】:

      设置:

       SharedPreferences.Editor sh_ed = getPreferences(MODE_PRIVATE).edit();
       sh_ed.putString("URL","http://myURL/example1");
       editor.apply();
      

      获得:

      SharedPreferences sh_pr = getPreferences(MODE_PRIVATE); 
      String myUrl = sh_pr.getString("URL", null);
      

      【讨论】:

        猜你喜欢
        • 2012-05-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-17
        • 2019-06-20
        • 2013-09-10
        • 2011-09-13
        • 2012-10-24
        • 2019-12-04
        相关资源
        最近更新 更多