Search code examples
androidnullpointerexceptionhandlerrunnableonresume

Android Runnable stop handler after application Resumed


I have an application which from inside a fragment runs a postDelayed task every 1 second using a handler which is enabled/disabled using a checkbox. (Working fine)

When the app is paused, the runnable still has effect in the background as I want it to. However, If I resume the app, I want to be able to stop the handler if checkBox becomes unChecked using handler.removeCallbacks(runnable) but I get a NullPointerException.

Is there a way to do this?

@Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    if(checkBox1.isChecked()) {
      if(deviceStart()==0) {
        //Failed to start service
        checkBox1.setChecked(false);
        Toast.makeText(getActivity(), "Failed to Start Service. Please Try Again...",Toast.LENGTH_SHORT).show();
      } else {
          handler = new Handler();
          handler.postDelayed(runnable, 1000);
      }
    } else {
      if(pocketHaloStop()==0) {
        //Failed to stop service
        checkBox1.setChecked(true);
        Toast.makeText(getActivity(), "Failed to Stop Service. Please Try Again...",Toast.LENGTH_SHORT).show();
      } else {
        handler.removeCallbacks(runnable); //This generates Null Pointer Exception if app is Resumed!
      }
    }
  });

Here is the code for the Runnable and onPause / onResume:

private Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			/* do what you need to do */

			handler.postDelayed(this, 1000);
		}
	};
    
    private void save(final boolean isChecked) {
		mContext = getActivity();
		SharedPreferences settings = mContext.getSharedPreferences("settings", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("Check", isChecked);
		editor.commit();
	}

	private boolean load() { 
		mContext = getActivity();
		SharedPreferences settings = mContext.getSharedPreferences("settings", Context.MODE_PRIVATE);
		return settings.getBoolean("Check", false);
	}

    @Override
    public void onResume() {
    	super.onResume();
    	checkBox1 = (CheckBox)view.findViewById(R.id.checkEnable);
		checkBox1.setChecked(load());
		
    }

    @Override
    public void onPause() {
        super.onPause();
        save(checkBox1.isChecked());
        checkBox1.setOnClickListener(null);
    }


Solution

  • move the creation of the Handler to the onCreate().

     ....
     public void onCreate(Bundle savedInstanceState) {
         ...
    
         handler = new Handler();
    
         ...
     }