Search code examples
javaandroidandroid-handler

How to fix error at handler.removeCallbacks resulting app crash?


I am trying to create a sample app that draws the route between two locations (like the uber app) I have a toggle switch to turn the location on or off in the app.The app works fine and draws the route but when i just launch the app and toggle the location switch to on and then toggle it to off the app crashes showing a nullpointerexception at handler.removeCallbacks(drawPathRunnable); I tried to figure out the error but I failed. Here's my code

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
    location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean isOnline) {
            if(isOnline)
            {
                startLocationUpdates();
                displayLocation();
                Snackbar.make(mapFragment.getView(),"You are online", Snackbar.LENGTH_SHORT)
                        .show();
            }
            else
            {
                stopLocationUpdates();
                mCurrent.remove();
                mMap.clear();
                handler.removeCallbacks(drawPathRunnable);
                Snackbar.make(mapFragment.getView(),"You are offline", Snackbar.LENGTH_SHORT)
                        .show();
            }
        }
    });

I have declared handler at the top of my code private Handler handler;

Please explain the answer and the cause of the error.


Solution

  • You should initialize your handler object

    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        handler =new Handler();
        // Obtain the ......