I try to bind the service to the fragment in the same way as I did successfully in action, but when I try to call a method in the service, I get a NullPointerException - obviously because the service is null. Now there are some problems with service binding in onStart or am I just doing it wrong?
@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; }
Edit: Sorry. I thought that it was my mistake that I did not ask this question. mConnection is a ServiceConnection and looks like this:
private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) {
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 will be the exact place where the exception is thrown: case POPULATE_ID:
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;
android android-fragments
CodePrimate
source share