【问题标题】:Why is this value null?为什么这个值是空的?
【发布时间】:2016-02-11 00:54:11
【问题描述】:

我成功地从我的mainActivity 中创建、保存和检索我的共享首选项,但我无法从我的服务中获取它...

由于某种原因,当我尝试从后台服务中检索它时,我的共享首选项为空...

我在 onCreate 中初始化了我的偏好:

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

在 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();

一切正常,但是当我尝试从我的服务访问我的首选项时,我得到 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");
    }

令我失望的是,我得到了日志Dagnabit it its null。为什么它是空的?我可以向您保证,它适用于我的主要活动,因为当我从我的共享偏好中访问它时,我能够显示我的共享偏好中的所有数据。所以我知道它不应该为空......但出于某种原因

谢谢,

鲁基尔

编辑:

我实际上使用内容观察器注册了一个音量监听器,并且我正在从那里访问首选项。这是在服务中:

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

这里是内容观察者:

   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);

}

【问题讨论】:

  • 我注意到在最后一段代码中,使用了 var preferences 而不是 contactsPrefs。这是故意的吗?
  • @flkes 是的,我已经更新了我的问题以显示我的偏好的实例化。 :)
  • @flkes 我在服务中使用preferences = PreferenceManager.getDefaultSharedPreferences(c); 。是这个问题吗?
  • 不,不确定。我只是想知道!尽管stackoverflow.com/questions/5950043/… 这个链接可能会有所帮助
  • 是否需要添加MODE_PRIVATE参数?

标签: java android arrays database string


【解决方案1】:

尝试使用应用程序上下文获取共享首选项引用,如下所示:

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

注意: 如果仍然为 null,则从服务的 onStart() 方法获取共享首选项,而不是在 onCreate() 中进行。

编辑: 我测试了它的工作原理

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);
    }
}
}

【讨论】:

  • 请查看我对我的问题的编辑,它在侦听器的服务中。可以吗?
  • 代码应如下所示 @Override public int onStartCommand(Intent intent, int flags, int startId) { contactsPrefs = getApplicationContext().getSharedPreferences("contactsPrefs", MODE_PRIVATE); //创建一个共享首选项 return super.onStartCommand(intent, flags, startId); }
  • 你看到我的编辑了吗?它实际上在内容观察者中,所以我得到Cannot resolve getApplicationContext()
  • 看我问题的底部
  • 哦,您正在将上下文引用传递给内容观察者,您可以使用它来获取共享首选项。
猜你喜欢
  • 2021-12-12
  • 2021-06-13
  • 1970-01-01
  • 2018-09-02
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
相关资源
最近更新 更多