Kumar Raja
Kumar Raja

Reputation: 51

My Android application crashes when I change screen orientation

In my application, network access is running in a thread. Whenever I change screen orientation, my application crashes. How might I resolve this?

Upvotes: 3

Views: 6306

Answers (4)

Anup Rojekar
Anup Rojekar

Reputation: 1103

Hi I think you should go through the Activity Life Cycle first.

Since whenever there is a change in the orientation OnCreate() method is called,

causes crashing of your application.

Best Regards, ~Anup

Upvotes: 1

Kumar Raja
Kumar Raja

Reputation: 51

Thanks for the Answers.. I have got solution by Implementing Activity Life cycle method OnStop. In that method I have just added the below code

@Override
public void onStop()
{
    super.onStop();
    if(thread!=null)
        thread.stop();
    if(dialog!=null)
        dialog.dismiss();
}

Upvotes: 2

ankita gahoi
ankita gahoi

Reputation: 1562

you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.

Start by adding the android:configChanges node to your Activity's manifest node

 android:configChanges="keyboardHidden|orientation"

Then within the Activity override the onConfigurationChanged method and call setContentView to force the GUI layout to be re-done in the new orientation.

@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);
  setContentView(R.layout.myLayout);
}

Upvotes: 1

Aleadam
Aleadam

Reputation: 40391

The activity actually stops and restarts every time the device orientation changes. You need to write your thread with that in mind, i.e. stopping the thread and restarting it when the device changes orientation, perhaps saving the state in between.

Upvotes: 1

Related Questions