这是为什么null值? [英] Why is this value null?

查看:274
本文介绍了这是为什么null值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地制作,保存和检索从我的共享preferences我的 mainActivity ,但我不能从我的服务得到它...

由于某些原因,我的共享preferences为空,当我试图从一个后台服务检索...

我初始化我preferences中的onCreate:

 联系人preFS = getShared preferences(接触preFS,MODE_PRIVATE); //创建共享preferences

中的onCreate保存的值:

 的MyEditor =接触prefs.edit();    SET<串GT;设置=新的HashSet<串GT;();
    set.addAll(contactArrayList);    myEditor.clear(); //共享preF清除当前值
    myEditor.putStringSet(contactSetKey,设置); //添加联系人
    myEditor.commit();

这一切是怎么回事,但是当我试图从我的服务访问我的preferences,我得到空:

  preferences = preferenceManager.getDefaultShared preferences(C); //参见下方的编辑更多信息


 如果(preferences.getStringSet(contactSetKey,NULL)!= NULL){
        contactArrayList.addAll(preferences.getStringSet(contactSetKey,NULL));        对(串号:contactArrayList){            number.substring(number.indexOf( - )+1); //从我的字串连字符之前取出的所有字符            Log.v(TAG,数);        }
    }其他{
        Log.v(TAGDagnabit它的空);
    }

和让我失望,我得到的日志 Dagnabit它的空。为什么是空?我可以向你保证,它从我的主要活动的作品,因为我能够从我的共享preferences显示所有我的数据,当我从我的共享preference访问它。所以,我知道,它不能为空...但它是出于某种原因

谢谢,

Ruchir

编辑:

其实,我注册使用内容观察者卷监听器,而我从那里accesing的preferences。下面是该服务:

  mSettingsContentObserver =新volumeCheck(这一点,新的处理程序());
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI,真的,mSettingsContentObserver);

下面是Content观察报:

 公共类volumeCheck扩展ContentObserver { 公共volumeCheck(上下文C,处理程序处理){
        超(处理); //创建一个新的处理程序
        上下文= C; //变量方面,前面定义,被设置为等于C,服务的上下文。        preferences = preferenceManager.getDefaultShared preferences(C);}


解决方案

尝试使用应用程序上下文得到共享preF参考如下图所示:

 联系人preFS =
          getApplicationContext()。getShared preferences(接触preFS
          MODE_PRIVATE); //创建共享preferences

请注意:
如果你仍然得到空门,然后从在onStart()的服务,而不是做它里面的onCreate()。

的方法共享preference

编辑:
我测试了其工作

 公共类MainActivity扩展AppCompatActivity {私人共享preferences preferences;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    preferences = preferenceManager.getDefaultShared preferences(getApplicationContext());
    共享preferences.Editor编辑器= preferences.edit();
    editor.putString(状态,成功);
    editor.apply();    getContentResolver()。registerContentObserver(ContactsContract.Contacts.CONTENT_URI,真实,
            新VolumeCheck(这一点,新的处理程序()));
}
}进口android.content.Context;
进口android.content.Shared preferences;
进口android.database.ContentObserver;
进口android.os.Handler;
。进口的Andr​​oid preference preferenceManager。
进口android.util.Log;
公共类VolumeCheck扩展ContentObserver {
私人最终共享preferences preferences;私人上下文的背景下;公共VolumeCheck(上下文C,处理程序处理){
    超(处理); //创建一个新的处理程序
    上下文= C; //变量方面,前面定义,被设置为等于C,服务的上下文。    preferences = preferenceManager.getDefaultShared preferences(c.getApplicationContext());
    字符串状态= preferences.getString(状态,);
    如果(!status.equalsIgnoreCase())
    {
        //得到了共享preference读取值
        Log.i(读值,地位);
    }
}
}

I am succesfully making, saving, and retrieving my shared preferences from my mainActivity, but I cant get it from my service...

For some reason, my shared preferences is null when I try to retrieve it from a background service...

I initialize my preferences in onCreate:

contactsPrefs = getSharedPreferences("contactsPrefs", MODE_PRIVATE); //Making a shared preferences

Save values in onCreate:

    myEditor = contactsPrefs.edit();

    Set<String> set = new HashSet<String>();
    set.addAll(contactArrayList);

    myEditor.clear(); //Clearing current values in shared pref
    myEditor.putStringSet("contactSetKey", set); //Adding contacts
    myEditor.commit();

All this is going fine, but when I try to access my preferences from my service, I get null:

    preferences = PreferenceManager.getDefaultSharedPreferences(c); //See edit at bottom for more info


if(preferences.getStringSet("contactSetKey", null) != null) {
        contactArrayList.addAll(preferences.getStringSet("contactSetKey", null));

        for (String number : contactArrayList) {

            number.substring(number.indexOf("-") + 1); //Remove all characters before the hyphen from my string

            Log.v(TAG, number);

        }
    }else{
        Log.v(TAG, "Dagnabit it its null");
    }

And to my disappointment, I get the log Dagnabit it its null. why is it null? I can assure you that it works from my main activity, because I am able to display all of my data from my shared preferences when I access it from my shared preference. So I know that it shouldn't be null...But it is for some reason

Thanks,

Ruchir

EDIT:

I actually register a volume listener using content observer, and I am accesing the preferences from there. Here is in the service:

 mSettingsContentObserver = new volumeCheck(this, new Handler());
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);

Here is the Content Observer:

   public class volumeCheck extends ContentObserver {

 public volumeCheck(Context c, Handler handler) {
        super(handler); //Creates a new handler
        context = c; //variable context, defined earlier, is set equal to c, context of service.

        preferences = PreferenceManager.getDefaultSharedPreferences(c);

}

解决方案

Try to get shared pref reference using application context as shown below:

contactsPrefs = 
          getApplicationContext().getSharedPreferences("contactsPrefs", 
          MODE_PRIVATE); //Making a shared preferences

Note: If you still getting null, then get the shared preference from onStart() method of the service instead of doing it inside onCreate().

EDIT: I tested and its working

public class MainActivity extends AppCompatActivity {

private SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Status","Success");
    editor.apply();

    getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,
            new VolumeCheck(this, new Handler()));
}
}



import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;


public class VolumeCheck extends ContentObserver {
private final SharedPreferences preferences;

private Context context;

public VolumeCheck(Context c, Handler handler) {
    super(handler); //Creates a new handler
    context = c; //variable context, defined earlier, is set equal to c, context of service.

    preferences = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
    String status = preferences.getString("Status", "");
    if(!status.equalsIgnoreCase(""))
    {
        // got the value read from shared preference
        Log.i("Reading value", status);
    }
}
}

这篇关于这是为什么null值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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