Service类中的SharedPreferences不起作用(Nullpointer)

时间:2014-02-27 19:38:35

标签: android nullpointerexception sharedpreferences android-context

我已经在这里做了很多研究来解决我的问题。我想,如果创建了一个活动,它会从服务类中执行一个方法。这是我的代码: MenuActivity.class:

public class MenuActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    BgService tracker = new BgService();
    tracker.changeIntent();
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
    int intentstarts = prefs.getInt("intentstarts",0);
    Toast.makeText(MenuActivity.this,String.valueOf(intentstarts), Toast.LENGTH_LONG).show();
    //...
}}

BgService.class

public class BgService extends Service {
public static String PREFS_NAME = "MyPrefsFile";
public void changeIntent(){
    Context context = getApplicationContext();
    SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    int intentstarts = prefs.getInt("intentstarts",0);
    intentstarts++;
    SharedPreferences.Editor edit = prefs.edit();
    edit.putInt("intentstarts", intentstarts).commit();
}}

logcat(我必须审查包名):

02-27 19:23:49.265: E/AndroidRuntime(1092): FATAL EXCEPTION: main
02-27 19:23:49.265: E/AndroidRuntime(1092): java.lang.RuntimeException: Unable to      start activity ComponentInfo{com.xxx.xxxxxxx/com.xxx.xxxxxxx.MenuActivity}: java.lang.NullPointerException
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.os.Looper.loop(Looper.java:123)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.ActivityThread.main(ActivityThread.java:3683)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at java.lang.reflect.Method.invokeNative(Native Method)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at java.lang.reflect.Method.invoke(Method.java:507)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at dalvik.system.NativeStart.main(Native Method)
02-27 19:23:49.265: E/AndroidRuntime(1092): Caused by: java.lang.NullPointerException
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at com.xxx.xxxxxxx.BgService.changeIntent(BgService.java:36)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at com.xxx.xxxxxxx.MenuActivity.onCreate(MenuActivity.java:33)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-27 19:23:49.265: E/AndroidRuntime(1092):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-27 19:23:49.265: E/AndroidRuntime(1092):     ... 11 more

如果能为我找到解决方案,那将是件好事

编辑:用“this”替换“context”后: 用这个代替上下文:

SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, 0);

02-27 21:01:57.560: E/AndroidRuntime(1316): FATAL EXCEPTION: main
02-27 21:01:57.560: E/AndroidRuntime(1316): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxxxxxx/com.xxx.xxxxxxx.MenuActivity}: java.lang.NullPointerException
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.os.Looper.loop(Looper.java:123)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.ActivityThread.main(ActivityThread.java:3683)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at java.lang.reflect.Method.invokeNative(Native Method)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at java.lang.reflect.Method.invoke(Method.java:507)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at dalvik.system.NativeStart.main(Native Method)
02-27 21:01:57.560: E/AndroidRuntime(1316): Caused by: java.lang.NullPointerException
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at com.xxx.xxxxxxx.BgService.changeIntent(BgService.java:36)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at com.xxx.xxxxxxx.MenuActivity.onCreate(MenuActivity.java:33)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-27 21:01:57.560: E/AndroidRuntime(1316):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-27 21:01:57.560: E/AndroidRuntime(1316):     ... 11 more

3 个答案:

答案 0 :(得分:3)

您需要将活动与服务绑定以调用服务方法。 示例代码 -

public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    LocalService getService() {
        // Return this instance of LocalService so clients can call public methods
        return LocalService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

/** method for clients */
public int getRandomNumber() {
  return mGenerator.nextInt(100);
 }
}

public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
protected void onStart() {
    super.onStart();
    // Bind to LocalService
    Intent intent = new Intent(this, LocalService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}

/** Called when a button is clicked (the button in the layout file attaches to
  * this method with the android:onClick attribute) */
public void onButtonClick(View v) {
    if (mBound) {
        // Call a method from the LocalService.
        // However, if this call were something that might hang, then this request should
        // occur in a separate thread to avoid slowing down the activity performance.
        int num = mService.getRandomNumber();
        Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    }
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};
}

详情可在此处找到 - http://developer.android.com/guide/components/bound-services.html#Binder 我认为扩展活页夹类对您来说已经足够了。其他方法也在这里描述。

答案 1 :(得分:1)

这是因为您在getApplicationContext()中使用了ServiceService本身是Context,因此请使用getApplicationContext()

答案 2 :(得分:0)

BgService tracker = new BgService(); - 亲爱的,你不是要自己实例化服务和活动。这些类由android实例化,这样它们就被赋予了一个上下文。在您的情况下,上下文仅为空 - 对于具有活动的类似情况,请参阅Why getApplicationContext() in constructor of Activity throws null pointer exception?

您必须在Android上阅读并重新考虑您的设计