【问题标题】:Shared preferences - Bundles intent共享首选项 - 捆绑意图
【发布时间】:2014-03-10 22:07:51
【问题描述】:

我正在尝试将共享首选项放在一个包中,以便我可以在另一个类中使用它。

例如,我有一个类可以查看共享首选项中的字符串。 然后我有另一个可以编辑字符串的类。

在我创建捆绑包的主类中:

  SharedPreferences sharedpreferences;

      Intent i = new Intent(getBaseContext(),verification.class);

       i.putExtra("sharedpreferences", sharedpreferences);

问题在于 putExtra。它适用于普通字符串,但不适用于捆绑包,任何想法,我认为它很简单

【问题讨论】:

  • 这些类在同一个应用程序中吗?如果是这样,您可以从应用中的任何类访问相同的 SharedPreferences,而无需使用 Intent 进行共享。

标签: java android sharedpreferences gettext settext


【解决方案1】:

当然Intent.putExtra(...) 适用于捆绑包

Intent.putExtra(String name, Bundle value);

无论如何,没有必要将SharedPreferences 作为Bundle 传递给下一个活动。 只需从下一个 Activity 本身检索 SharedPreferences

将内容保存到SharedPreferences

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Context);
Editor e = sp.edit();
e.putString("key", "value"); // save "value" to the SharedPreferences
e.commit();

SharedPreferences中检索东西:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Context);
String s = sp.getString("key", null); // get "value" from the SharedPreferences

这没什么意义,但这里是如何将StringSharedPreferences 放入Intent

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Context);
Intent i = new Intent(Context, YourActivity.class);
i.putExtra("key", sp.getString("key", null));

【讨论】:

  • 请参考我原来的问题,我正在尝试使用来自共享偏好的字符串
  • 我刚刚向您展示了如何从共享首选项中检索字符串。看看我的代码。
猜你喜欢
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
相关资源
最近更新 更多