2

I have an Activity with a Switch Control. With this switch control, the user can turn on/off a tcp server.

Now I have a similiar problem to here. If the Switch (and also the Server) is turned on and the orientation changes the onclicklistener is called again and so also the server is started again.

I tried to handle this by checking if the client is null:

OnCheckedChangeListener listener = new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {    
        if(isChecked) {
            if (client == null)
              startCubeSolverServer();
        } else {
            if (client != null)
              stutdownCubeSolverServer();
        }
    }
};

but because the client object is a private variable of my activity it is reset to null each orientation change.

Is there an easy fix to don't run the changeHandler if the value doesn't change in users view?

Community
  • 1
  • 1
TomBoo
  • 391
  • 1
  • 4
  • 11
  • 1
    instead of checking `client != null` you can use `sharedPreferences` and store a `String` or `boolean` value in `onPause()` and then perform the check in `onResume()`. – Rohan Kandwal Jul 13 '13 at 20:46
  • Good idea to use sharedPreferences! Do you also have an idea where I should handle the object of my server? – TomBoo Jul 13 '13 at 21:03
  • you can implement entire `OnCheckedChangeListener` function in onResume() and `SharedPreferences` in `onPause`. Also if my comments are useful mark them so. – Rohan Kandwal Jul 13 '13 at 21:07
  • why don't you just disable orientation change? go to your manifest file and set android:configChanges="orientation|screenSize" then you don't need to worry about your activity getting recreated. – Saeid Farivar Jul 14 '13 at 01:29

1 Answers1

1

The behavior of the system in your situation is correct. The onCheckedChanged should be called when orientation changes.

Now for your situation, if the tcp server is a service then you should move all of the initialization in the onCreate method of that service instead in the onStartCommand, doing so you don't have to do nothing when orientation changes since the service is only created once by the system and it doesn't matter how many times are you going to start it again.

Another solution is to handle the onClick event of your switch button instead the onCheckedChanged because the onClick will not fire up after the orientation changes. However if you do this you must study if the onClick method of your switch button fires before or after the checked state changes.

Hope this helps...

ChD Computers
  • 3,135
  • 3
  • 23
  • 33