问题描述:

I have an activity in my android app that calls an asynctask on onCreateView()

Here is my code :

 @Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_weeklyprofit);

fromDateTxt=(TextView)findViewById(R.id.fromDate);

toDateTxt = (TextView)findViewById(R.id.toDate);

GetXYPoints getXY = new GetXYPoints();

getXY.execute(fromDateTxt.getText().toString(),toDateTxt.getText().toString());

}

now my application needs to rotate, so i need to store data when rotate :

I have implemented this as below :

@Override

public void onSaveInstanceState(Bundle savedInstanceState) {

super.onSaveInstanceState(savedInstanceState);

savedInstanceState.putString("from", fromDateTxt.getText().toString());

savedInstanceState.putString("to", toDateTxt.getText().toString());

}

@Override

public void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);

SystemClock.sleep(500);

fromDateTxt.setText(savedInstanceState.getString("from"));

toDateTxt.setText(savedInstanceState.getString("to"));

GetXYPoints getXY = new GetXYPoints();

getXY.execute(fromDateTxt.getText().toString(),toDateTxt.getText().toString());

}

So i recall the asynctask again with restored data, my problem is that the activity run again when rotate and the it calls onRestoreInstanceState so how can i prevent the activity from calling the first asyncktask?

In other way what is the best solution to store data returned by an asynck task when screen is rotate?

网友答案:

i would suggest you to to make sure you actually need your activity to be reset on a screen rotation (the default behavior). Every time I've had issues with rotation I've added this attribute to my tag in the AndroidManifest.xml, and been just fine.

android:configChanges="keyboardHidden|orientation"

source How to handle an AsyncTask during Screen Rotation?

网友答案:

In your AndroidManifest.xml add following for prevent reloading activity when orientation change

android:configChanges="orientation|screenSize"

So, you'll have something like this:

<activity android:name="Activity"
android:configChanges="orientation|screenSize">
</activity>

Hope it works!

相关阅读:
Top