从不同的IntentService访问SharedPreferences

时间:2015-03-17 19:44:29

标签: android sharedpreferences intentservice

从IntentService内部访问shredPreferences时遇到问题

这是我得到的错误:

java.lang.RuntimeException: Unable to instantiate service com.androidbook.btdt.hour6.QuizSettingsActivity$UploaderService: java.lang.NullPointerException

时出现nullpointer异常
mGameSettings = getSharedPreferences(GAME_PREFERENCES,Context.MODE_PRIVATE);

这是代码:

public static  class UploaderService extends IntentService{

String DEBUG_TAG = UploaderService.class.getSimpleName();

SharedPreferences mGameSettings;



private UpLoadUserData upLoadUserData;

/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public UploaderService(String name) {
    super(name);
    mGameSettings = getSharedPreferences(GAME_PREFERENCES,Context.MODE_PRIVATE);
}

public UploaderService(){
    super("");
    mGameSettings = getSharedPreferences(GAME_PREFERENCES,Context.MODE_PRIVATE);
}

这就是我启动IntentService的方式:

    Intent uploadService = new Intent(this,UploaderService.class);
    startService(uploadService);

1 个答案:

答案 0 :(得分:1)

我认为你需要在startService函数中执行该行而不是构造函数。我知道至少对于构造时的活动,Context没有完全建立,所以很多调用都会失败。我相信服务是一样的。