title: How do I bind a service from a fragment
body: <p>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?</p>
  
  <pre><code>@Override
  public void onStart() {
      super.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);
  }
  
  @Override
  public void onStop() {
      super.onStop();
      getActivity().unbindService(mConnection);
      getActivity().unregisterReceiver(receiver);
      mBound = false;
  }
  </code></pre>
  
  <p><em>edit:</em> Sorry. That's my mistake for not giving this question enough thought. mConnection is a ServiceConnection and looks like this :</p>
  
  <pre><code>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;
      }
  };
  </code></pre>
  
  <p>Stacktrace : </p>
  
  <pre><code>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)
  </code></pre>
  
  <p>And this is would be the exact place where the exception is thrown : 
  case POPULATE_ID:</p>
  
  <pre><code>        if (hasData) {
              return false;
          }
          if(!mBound)
              getActivity().bindService(new Intent(getActivity().getApplicationContext(), LiteTrickService.class), mConnection, Context.BIND_AUTO_CREATE);
          mService.refreshPlayers(); // Null Pointer Exception as mService is null
          pBar.setVisibility(View.VISIBLE);
          return true;
  </code></pre>