0

, i've implemented an application running a backgroundservice . A couple weeks ago , things were working but now it doesn't running and i got the error : java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ComponentName android.content.Intent.getComponent()' on a null object reference . Here's what i have implemented :

//Service code :

@RequiresApi(api = Build.VERSION_CODES.R)
public class TimeService extends Service {
    private final static String TAG = TimeService.class.getName();
  
   
    @Override
    public void onCreate() {
        super.onCreate();
      

       //Code to run

}
               

      @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        
        //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        //                startForegroundService(new Intent(this, TimeService.class));
        //                Log.d("TAG","service has started ");
        //
        //            }
        //        }
             //   Log.d("TAG","service has started ");
                Intent startServiceIntent = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                    startServiceIntent = new Intent( this, TimeService.class);
                }
                startService(startServiceIntent);
            }
  • 2
    Of course you're getting a null pointer exception. You are initializing `startServiceIntent` as `null` and only assigning a non null value to it inside an if statement. We have no way to know if your condition is ever true, so we don't know if `startServiceIntent = new Intent( this, TimeService.class);` ever executes. Add a breakpoint in that line and run with debugger to see if it's actually trying to execute. If its not then you have your answer. – Dasph Mar 09 '23 at 14:50

0 Answers0