Home » Android » android – How do I bind a service from a fragment

android – How do I bind a service from a fragment

Posted by: admin June 15, 2020 Leave a comment


I’m attempting to bind a service from a fragment the same way I have done succesfully in an activity, but when I try to call a method on the service I get a NullPointerException – Obviously because the service is null. Now is there some problem with binding to the service in onStart or am I simply doing it wrong?

public void onStart() {

    Intent intent = new Intent(getActivity(), LiteTrickService.class);
    getActivity().registerReceiver(receiver, new IntentFilter(LiteTrickService.BROADCAST_ACTION));
    getActivity().registerReceiver(receiver, new IntentFilter(LiteTrickService.BROADCAST_FAIL));
    getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

public void onStop() {
    mBound = false;

edit: Sorry. That’s my mistake for not giving this question enough thought. mConnection is a ServiceConnection and looks like this :

private ServiceConnection mConnection = new ServiceConnection() 

    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;

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

Stacktrace :

01-03 15:21:22.355: E/AndroidRuntime(12360): FATAL EXCEPTION: main
01-03 15:21:22.355: E/AndroidRuntime(12360): java.lang.NullPointerException
01-03 15:21:22.355: E/AndroidRuntime(12360):    at lite.hattrick.players.PlayerRankingFragment.onOptionsItemSelected(PlayerRankingFragment.java:205)

And this is would be the exact place where the exception is thrown :

        if (hasData) {
            return false;
            getActivity().bindService(new Intent(getActivity().getApplicationContext(), LiteTrickService.class), mConnection, Context.BIND_AUTO_CREATE);
        mService.refreshPlayers(); // Null Pointer Exception as mService is null
        return true;
How to&Answers:

I solved the problem. Turns out I had forgotten to provide service declaration in my manifest with its correct package name.

by changing

<service android:name=".LiteTrickService" />


<service android:name="lite.hattrick.services.LiteTrickService" />

I solved the problem and the service is now connecting as expected.


Your NullPointerException is on the mService variable. As you call bindService(), the Activity binds to the Service on it’s own thread. This means that your code will keep running while the service is binding. This results in your mService variable still being null.

What you could do is move the code that has to run after the Service has bound, to the onServiceConnected() method of your mConnection. This will assure that the mService variable will point to your service, and will not be null.