【问题标题】:TextView that gets Value from SharedPreferences shows nothing, though there should be default values从 SharedPreferences 获取值的 TextView 什么也不显示,尽管应该有默认值
【发布时间】:2016-09-08 09:40:55
【问题描述】:

我遇到了SharedPreferences 的问题,这有点奇怪。

我有一个Activity,它在ViewPager 中包含一个Fragment。该片段显示一个图标和文本。您可以从另一个活动更改此片段中显示的图标(复选标记或十字,复选标记是默认值)和文本。然后将数据传输到带有意图的 Fragment Container Activity。

现在我想保存文本和选择的图标,因此片段会显示相同的文本和图标,即使您关闭应用程序并稍后重新启动它也是如此。

所以我尝试使用SharedPreferences 来实现这一点,但是当我尝试它时,我的片段显示没有文本和错误图标,尽管我设置了默认值并且图标始终是十字,不管它是什么之前虽然默认图标应该是复选标记。

当我的 Fragment 使用用户之前在活动中输入的数据创建时,我将值保存在 onCreateView() 中。

保存:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();

            Bundle bundle = getArguments();

            String city = bundle.getString("city");
            String country = bundle.getString("country");
            int ok = bundle.getInt("ok");

            TextView cityText = (TextView) view.findViewById(R.id.city_name);
            TextView countryText = (TextView) view.findViewById(R.id.country_name);
            ImageView shownIcon = (ImageView) view.findViewById(R.id.ok_bad_icon);

            cityText.setText(city);
            countryText.setText(country);

            if(ok == 1){
             shownIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.checkmark_icon, null));
            }else{
                shownIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.bad_icon, null));
            }

            editor.putString("city", city);
            editor.putString("country", country);
            editor.putInt("okBad", ok);
            editor.putString("saved", "Yes");

            editor.apply();

然后,我在我的 Activity 的 onCreate() 中获得了包含 Fragment 的值:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
String storedSave = sharedPref.getString("saved", "no");

    if (storedSave.equalsIgnoreCase("yes")){

    String storedCity = sharedPref.getString("city", "berlin");
    String storedCountry = sharedPref.getString("country", "germany");
    int storedOkBad = sharedPref.getInt("okBad", 1);

        Bundle extras = new Bundle();

        StatusFragment savedFragment = new StatusFragment();

        extras.putString("city", storedCity);
        extras.putString("country", storedCountry);
        extras.putInt("okBad", storedOkBad);

        savedFragment.setArguments(extras);

        mSectionsPagerAdapter.addFragment(savedFragment, extras.getString("city"));
    }

我在 stackoverflow 上搜索了不同问题的答案,但没有一个对我有用,例如:

Cannot get value from sharedpreferences

Shared Preferences get lost after shutting down device or killing the app

Shared Preferences reset data when app is force closed or device is restarted

SharedPreferences keep getting default value

How to use SharedPreferences in Android to store, fetch and edit values

我还尝试使用Log.w()Toast.makeText() 打印城市的值,但没有显示任何内容,就像它被完全跳过一样,但是为什么我的Activity 中有一个Fragment 然后在重启后跳过这个不加?

我是否必须在编辑时使用edit().putString().apply(),或者我可以使用editor.putString() 添加值,即使它已经存在?

很抱歉,这可能是一些微不足道的事情,但我使用 Fragments 的次数不多,我现在是第一次使用 SharedPreferences

我会很感激每一个有用的答案。

【问题讨论】:

  • 以这种方式初始化 shred Preference preferences = mContext.getSharedPreferences("Your shared Pref name ", Context.MODE_PRIVATE);
  • @Himani,这样做没有问题,因为getPreferences 只需通过传入此活动的类名来调用底层 getSharedPreferences(String, int) 方法
  • 这里没有足够的信息来回答您的问题。你如何在持有片段的活动中初始化共享偏好?您如何在您提到的其他活动中对其进行初始化和写入?
  • 我添加了初始化,在用户可以编辑的活动中,我使用了一个意图,没有共享偏好
  • 我尝试将 getPreferences(Context.MODE_PRIVATE) 替换为 getApplicationContext().getSharedPreferences("com.fragmentdata.myapp.www", Activity.MODE_PRIVATE) 但总是得到相同的结果,只有默认值:(

标签: android android-fragments sharedpreferences


【解决方案1】:

尝试像这样更改您的SharedPreference 初始化并在onActivityCreated() 中调用getActivity()

PreferenceManager.getDefaultSharedPreferences(getActivity())

建议使用apply() 而不是commit()。编辑更改后,调用:

editor.apply()

【讨论】:

  • 感谢您的 apply() 提示,但不幸的是它并没有改变我得到的任何结果:/
【解决方案2】:

在片段的onActivityCreated() 方法中调用getActivity()。 在onCreateView() 中可能会返回空上下文。请检查并在onActivityCreated() 方法中移动您的代码。

【讨论】:

  • 对不起,但这并没有改变任何事情:/
【解决方案3】:

在观察您的代码时,我注意到密钥不匹配。

在捆绑中保存时,您使用了密钥 - okBad

    Bundle extras = new Bundle();
    ....
    extras.putInt("okBad", storedOkBad);

在检索片段时,您使用了密钥 - 好的

    Bundle bundle = getArguments();
    ...
    int ok = bundle.getInt("ok");

所以请先纠正它。

【讨论】:

  • "ok" 是我从用户编辑数据的活动中传递的变量的键,okBad 是我想在我的共享首选项中使用的键
  • @boehmP 在您发布的活动的 onCreate 中,在创建捆绑包时,您使用“okBad”作为键。在片段的 onCreateView 中,您首先从使用“ok”作为键的包中提取。请再次检查。如果您发布不正确,请更正您的问题。在这里,我什至没有提到共享偏好。我只是指您用作参数的捆绑包。
【解决方案4】:

问题现在解决了。我不得不使用getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE); 并且我在捆绑包和偏好中的一些变量混淆了。我已经纠正了这个问题,现在可以正常工作了:)感谢您的回答。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 2019-08-20
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多