获取活动/普通类的Andr​​oid共享preferences值 [英] Get Android shared preferences value in activity/normal class

查看:101
本文介绍了获取活动/普通类的Andr​​oid共享preferences值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一个存储用户设置的共享preference活动,现在我想在一个活动或普通的Java class.please值提供了一个解决方案或例子,我已经尝试过这种code,但失败了

I have made a shared preference activity that store the user settings, now i want to get values in a activity or normal java class.please provide a solution or example i have already tried this code but failed.

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    SharedPreferences channel=this.getSharedPreferences(strFile, Context.MODE_PRIVATE);
    strChannel=channel.getString(keyChannel,"Default").toString();
    Toast.makeText(getApplicationContext(), strChannel, Toast.LENGTH_LONG).show();
}                     

在此code strfile 的如。 com.android.pack.ClassName 共享preference活动从值是牵强,而且keyChannel是关键即在共享preference活动

in this code strfile for eg. com.android.pack.ClassName is SharedPreference Activity from values to be fetched, and keyChannel is key that is same in SharedPreference Activity.

请提供了解决方案。

推荐答案

如果你有一个共享preferenceActivity由你救了你的价值观

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

如果该值保存在共享preference一个活动,然后这是挽救它的正确方法。

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

这是你如何检索值。

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

另外要注意,您可以在非活动类也这样做,但唯一的条件是,你需要传递活动的背景下。使用此上下文来获取共享preferences。

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

这篇关于获取活动/普通类的Andr​​oid共享preferences值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆