Skip to main content

Posts

Showing posts with the label AsyncTask

Retain AsyncTask when configuration change

One of the frequent facing situation in Android is how to handle configuration change such as device rotation, soft keyboard and so on. For example, what happens if you rotate the device when you download a file using AsyncTask? The Android would create your Activity again to load the proper configuration including layout. The lifecycle methods(onCreate - onStart - onResume) will be called again and you can get data onCreate() if you have saved any data onSavedInstance(). However, your AsyncTask lost pipeline to your Activity and the code of executing the AsyncTask will be called again. This is not definitely what we want. Let's have a look at code how to avoid it: I'm going to create a simple app to display weather using Open Weather API for demo. We need one Activity, one Fragment for UI ListView first. MainActivity.java import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bun...