Hi I'm implementing a custom asynctaskloader to load data in the background. The problem is when the user goes back to the activity after he minimizes the app(or pick photo from gallary), all the asynctaskloaders associated with the activity and asynctaskloaders associated with the fragments in the activity start all over again.
How can I prevent the loader to restart the loading process when the activity restarts?
My baseAsynctaskLoader class:
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
public abstract class BaseAsyncTaskLoader extends AsyncTaskLoader{
private static final String TAG = "BaseAsyncTaskLoader";
protected Context context;
protected Object mData;
public BaseAsyncTaskLoader( Context context ) {
super(context);
Log.d(TAG, "BaseLoader");
this.context = context.getApplicationContext();
}
#Override
public abstract Object loadInBackground();
#Override
public void deliverResult(Object data){
Log.d( TAG, "deliverResult" );
if (isReset()) {
return;
}
mData = data;
if (isStarted()) {
super.deliverResult(data);
}
}
#Override
protected void onStartLoading(){
Log.d( TAG, "onStartLoading" );
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
#Override
protected void onStopLoading(){
Log.d( TAG, "onStopLoading" );
cancelLoad();
}
#Override
protected void onReset(){
Log.d( TAG, "onReset" );
super.onReset();
onStopLoading();
if(mData !=null){
mData=null;
}
}
#Override
public void onCanceled(Object data){
Log.d( TAG, "onCanceled" );
super.onCanceled(data);
}
}
Loader class sample:
public class AddDetailService extends BaseAsyncTaskLoader{
Activity activity;
Bundle bundle;
String outputstringrespone="";
public AddCarService(Activity activity, Bundle bundle){
super(activity);
this.activity = activity;
this.bundle = bundle;
}
#Override
public Object loadInBackground(){
try{
int userId = bundle.getInt(USER_ID);
int modelId = bundle.getInt(MODEL_ID);
outputstringrespone = addDetails(userId, modelId);
}catch(Exception e){
Log.d(TAG, e.toString());
}
return null;
}
#Override
public void deliverResult(Object data){
super.deliverResult(data);
Log.d(TAG,"output--"+outputstringrespone);
if(outputstringrespone.equalsIgnoreCase("Success")){
Toast.makeText(activity, "Details Added Successfully", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(activity, "Details not added",Toast.LENGTH_SHORT).show();
}
}
}
LoaderCallback in activity:
getLoaderManager().initLoader(LoaderId.ADD_DETAIL, bundle, addDetailsCallbacks);
LoaderManager.LoaderCallbacks addDetailsCallbacks = new LoaderManager.LoaderCallbacks(){
#Override
public Loader onCreateLoader(int id, Bundle args){
return new AddDetailService(getActivity(), args);
}
#Override
public void onLoadFinished(Loader loader, Object data){
getLoaderManager().destroyLoader(LoaderId.ADD_DETAIL);
}
#Override
public void onLoaderReset(Loader loader){
}
};
This is the desired behavior of LoaderManager framework - it takes care of reloading the data with the initiated Loaders in case the enclosing Activity or Fragment get re-created.
In fact, some implementations of Loaders do not reload the data, but simply provide access to the latest data that has been cached internally.
Bottom line: you observe correct behavior of LoaderManager framework.
It is not clear what it is you're trying to accomplish with your Loader, but it looks like you chose an incorrect tool. If your goal is to perform the action just once, then you should use AsyncTask instead of Loaders.
Related
Some background information:
I am using a Activity>ParentFragment(Holds ViewPager)>Child fragments.
Child Fragments are added dynamically with add, remove buttons.
I am using MVP architecture
Actual Problem:
In child fragment, we have listview that populates using an asynctaskloader via a presenter.
Child Fragment:
//Initialize Views
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_search_view_child, container, false);
.......
mSearchViewPresenter= new SearchViewPresenter(
getActivity(),
new GoogleSuggestLoader(getContext()),
getActivity().getLoaderManager(),
this, id
);
SearchList list=new SearchList();
//requestList from presenter
searchListAdapter =new SearchViewListAdapter(getActivity(), list, this);
listView.setAdapter(searchListAdapter);
......
return root;
}
#Override
public void onResume(){
super.onResume();
mSearchViewPresenter.start();
searchBar.addTextChangedListener(textWatcher);
}
In the presenter class we have:
public SearchViewPresenter(#NonNull Context context, #NonNull GoogleSuggestLoader googleloader,#NonNull LoaderManager loaderManager,
#NonNull SearchViewContract.View tasksView, #NonNull String id) {
// mLoader = checkNotNull(loader, "loader cannot be null!");
mLoaderManager = checkNotNull(loaderManager, "loader manager cannot be null");
// mTasksRepository = checkNotNull(tasksRepository, "tasksRepository cannot be null");
mSearchView = checkNotNull(tasksView, "tasksView cannot be null!");
mSearchView.setPresenter(this);
searchList=new SearchList();
this.googleLoader=googleloader;
this.context=context;
this.id=loaderID;
// this.id=Integer.parseInt(id);
}
#Override
public void start() {
Log.d("start>initloader","log");
mLoaderManager.restartLoader(1, null, this);
}
//TODO implement these when you are ready to use loader to cache local browsing history
#Override
public android.content.Loader<List<String>> onCreateLoader(int i, Bundle bundle) {
int loaderid=googleLoader.getId();
Log.d("Loader: ", "created");
googleLoader=new GoogleSuggestLoader(context);
googleLoader.setUrl("");
googleLoader.setUrl(mSearchView.provideTextQuery());
return googleLoader;
}
#Override
public void onLoadFinished(android.content.Loader<List<String>> loader, List<String> data) {
Log.d("Loader: ", "loadFinished");
searchList.clear();
for (int i = 0; i < data.size(); ++i) {
searchList.addListItem(data.get(i), null, LIST_TYPE_SEARCH, android.R.drawable.btn_plus);
Log.d("data Entry: ",i+ " is: "+searchList.getText(i));
}
mSearchView.updateSearchList(searchList);
}
#Override
public void onLoaderReset(android.content.Loader<List<String>> loader) {
}
Also we have this code in the presenter that is triggered by a edittext box on the fragment view being edited.
#Override
public void notifyTextEntry() {
//DETERMINE HOW TO GIVE LIST HERE
// Dummy List
Log.d("notifyTextEntry","log");
if(googleLoader==null)googleLoader=new GoogleSuggestLoader(context);
googleLoader.setUrl(mSearchView.provideTextQuery());
// mLoaderManager.getLoader(id).abandon();
mLoaderManager.getLoader(1).forceLoad();
mLoaderManager.getLoader(1).onContentChanged();
Log.d("length ", searchList.length().toString());
// googleLoader.onContentChanged();
}
Lastly we have the loader here:
public class GoogleSuggestLoader extends AsyncTaskLoader<List<String>>{
/** Query URL */
private String mUrl;
private static final String BASE_URL="https://suggestqueries.google.com/complete/search?client=firefox&oe=utf-8&q=";
private List<String> suggestions =new ArrayList<>();
public GoogleSuggestLoader(Context context) {
super(context);
this.mUrl=BASE_URL;
}
public void setUrl(String mUrl){
this.mUrl=BASE_URL+mUrl;
};
#Override
protected void onStartLoading() {forceLoad(); }
#Override
public List<String> loadInBackground() {
if (mUrl == null) {
return null;
}
try {
suggestions = new ArrayList<>();
Log.d("notifyinsideLoader","log");
String result=GoogleSuggestParser.parseTemp(mUrl);
if(result!=null) {
JSONArray json = new JSONArray(result);
if (json != null) {
JSONArray inner=new JSONArray((json.getString(1)));
if(inner!=null){
for (int i = 0; i < inner.length(); ++i) {
//only show 3 results
if(i==3)break;
Log.d("notifyinsideLoader",inner.getString(i));
suggestions.add(inner.getString(i));
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return suggestions;
}
}
So the problem:
The code loads the data fine to the listview on the fragment. When orientation changes loader is not calling onLoadFinished. I have tested the loader and it is processing the data fine.
I have already tried forceload and onContentChanged in the presenter to no avail.
If you need anymore info or if I should just use something else like RxJava let me know. But I would really like to get this working.
Before you ask I have seen similar problems like: AsyncTaskLoader: onLoadFinished not called after orientation change however I am using the same id so this problem should not exist.
The answer was on this page AsyncTaskLoader doesn't call onLoadFinished
but details were not given as to how to move to this.
So let me explain here for anyone else with this problem in future.
Support library is meant for fragments. So the class that is in charge of callbacks has to be importing AND implementing the correct methods from the support library. Same as if you are using MVP your presenter must extend from support loadermanager.
i.e: import android.support.v4.app.LoaderManager; Then implement correct callbacks.
Like
#Override
public android.support.v4.content.Loader<List<String>> onCreateLoader(int i, Bundle bundle) {
...
return new loader
}
and
#Override
public void onLoadFinished(android.support.v4.content.Loader<List<String>> loader, List<String> data) {
//do something here to your UI with data
}
Secondly: The loader itself must be extending from support asynctaskloader.
i.e: import android.support.v4.content.AsyncTaskLoader;
I'm using android.support.v4.content.AsyncTaskLoader to load data into a support.v4.fragmentbut when the configuration changes i.e : rotate the screen getLoaderManager().initLoader(); always returns a new loader thus loadInBackground() is called again . When I tried to use a normal fragment not the support.v4 version and changed to the normal AsyncTaskLoader every thing worked as expected ,so i'm not sure if this is a bug in the support library or what?
TestAsync.class:
import android.support.v4.content.AsyncTaskLoader;
public class TestAsync extends AsyncTaskLoader<List<Movie>> {
public TestAsync(Context context) {
super(context);
}
#Override
public void deliverResult(List<Movie> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<Movie> oldData = mData;
mData = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldApps' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldData != null) {
onReleaseResources(oldData);
}
}
#Override
protected void onStartLoading() {
super.onStartLoading();
if (mData != null || oneShot){
deliverResult(mData);
}else {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override public void onCanceled(List<Movie> data) {
super.onCanceled(data);
// At this point we can release the resources associated with 'apps'
// if needed.
onReleaseResources(data);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (mData != null) {
onReleaseResources(mData);
mData = null;
}
}
protected void onReleaseResources(List<Movie> apps) {
// For a simple List<> there is nothing to do. For something
// like a Cursor, we would close it here.
}
}
BrowseMoviesActivityFragment:
public class BrowseMoviesActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Movie>> {
#Override
public Loader<List<Movie>> onCreateLoader(int id, Bundle args) {
return new TestAsync(mContext);
}
#Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
if (data != null) {
if (adapter.isEmpty()){
adapter.add(data);
gridView.setAdapter(adapter);
}else {
adapter.add(data);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onLoaderReset(Loader<List<Movie>> loader) {
adapter = new BrowseMoviesAdapter(getActivity(),new ArrayList<Movie>());
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = new Bundle();
getLoaderManager().initLoader(id, args, this);
}
}
BrowseMoviesActivity:
import android.support.v7.app.AppCompatActivity;
public class BrowseMoviesActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse);
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
BrowseMoviesActivityFragment browseFragment = (BrowseMoviesActivityFragment) fm.findFragmentByTag(TAG_BROWSE_FRAGMENT);
if (savedInstanceState == null){
if (browseFragment==null){
browseFragment = new BrowseMoviesActivityFragment();
fm.beginTransaction().replace(R.id.browse_container, browseFragment).commit();
}
}
I am using the support library and am using an AsyncTaskLoader. Why doesn't the constructor of the AsycTaskLoader not accepting a Fragment as a parameter?
I only want the AsyncTaskLoader to start loading data when it is called or initialized inside my fragments. But as of now, at anytime the Activity goes to onResume it restarts all the loaders I initialized on different fragments. I believe this is mainly because I am passing fragment.getActivity() in the constructor of my AsyncTaskLoader instances.
Any way to do this?
So far, I am wrapping the initialization of the loaders in a fragment and each have an inner AsyncTaskLoader, which I customized as well. Then when the fragment is initialized, in the onCreateView method, I then call the method like so :
initLoader();
initLoader() method
public Loader<Object> initLoader() {
return getLoaderManager().initLoader(LOADER_ID.DUMMIES, null, new LoaderCallbacks<Object>() {
#Override
public Loader<Object> onCreateLoader(int id, Bundle args) {
Loader<Object> loader = new CustomLoader<Object>(getActivity()) {
#Override
public Object loadInBackground() {
return DummyGenerator.generateDummyEntriesToDb();;
}
};
return loader;
}
#Override
public void onLoadFinished(Loader<Object> loader, Object data) {
setToDb(data);
}
#Override
public void onLoaderReset(Loader<Object> loader) {
}
});
}
CustomLoader.java - generic implementation I suited to my needs. The releaseResources method is not filled in but I left it there for future usage.
public class CustomLoader<T> extends AsyncTaskLoader<T> {
T mData;
public CustomLoader(Context context) {
super(context);
}
#Override
public T loadInBackground() {
return null;
}
#Override
public void deliverResult(T data) {
if (isReset()) {
releaseResources(data);
return;
}
T oldData = mData;
mData = data;
if (isStarted()) {
super.deliverResult(data);
}
if (oldData != null && oldData != data) {
releaseResources(oldData);
}
}
#Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
onStopLoading();
if (mData != null) {
releaseResources(mData);
mData = null;
}
}
#Override
public void onCanceled(T data) {
super.onCanceled(data);
releaseResources(data);
}
public void releaseResources(T data) {
}
}
The generateDummyEntriesToDb method is working fine just creating list of the objects I am using, as well as the setToDb() method. The problem is when the activity goes to onResume the loadnBackground() method is called again thus I am compelled to think that all the other loaders behave the same way.
The Context provided should be the Activity attached to the Fragment. Be sure you are initializing the loader via the LoaderManager as it is tied to the appropriate object life cycle. So when initializing from within a Fragment, you should use Fragment.getLoaderManager(). Then call LoaderManager.initLoader() appropriately.
I have this fragment:
public class ResultFragment extends Fragment implements LoaderCallbacks{
public static ResultFragment newInstance(Bundle args) {
ResultFragment fragment = new ResultFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().getSupportLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<EstateSearch> onCreateLoader(int id, Bundle args) {
return new RESTLoader(getActivity(), "http://etc");
}
#Override
public void onLoadFinished(Loader<EstateSearch> loader, EstateSearch es) {
}
#Override
public void onLoaderReset(Loader<EstateSearch> loader) {
}
}
The AsyncTaskLoader looks like this:
public class RESTLoader extends AsyncTaskLoader {
private String searchUrl;
public RESTLoader(Context context, String searchUrl) {
super(context);
this.searchUrl = searchUrl;
}
#Override
public EstateSearch loadInBackground() {
EstateSearch es = null;
try {
Network Stuff
} catch (Exception e) {
}
return es;
}
#Override
public void deliverResult(EstateSearch es) {
super.deliverResult(es);
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
}
}
The app crashes with a mysterious (at least to me) error:
http://i46.tinypic.com/260fw43.png
From putting in some Log.ds I know that the constructor of the AsyncTaskLoader isn't even called. I already tried to move the init() of the loader to later parts of the fragment lifecycle. The fragment is within a ViewPager btw if that's important. The AsyncTaskLoader works fine when called from an Activity.
Any ideas on what I'm doing wrong?
Okay, pretty embarassing mistake: I already had another Loader in the Activity that the fragment is attached to which also had the ID 0 :-/
I'm trying to use an AsyncTaskLoader to load data in the background to populate a detail view in response to a list item being chosen. I've gotten it mostly working but I'm still having one issue. If I choose a second item in the list and then rotate the device before the load for the first selected item has completed, then the onLoadFinished() call is reporting to the activity being stopped rather than the new activity. This works fine when choosing just a single item and then rotating.
Here is the code I'm using. Activity:
public final class DemoActivity extends Activity
implements NumberListFragment.RowTappedListener,
LoaderManager.LoaderCallbacks<String> {
private static final AtomicInteger activityCounter = new AtomicInteger(0);
private int myActivityId;
private ResultFragment resultFragment;
private Integer selectedNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myActivityId = activityCounter.incrementAndGet();
Log.d("DemoActivity", "onCreate for " + myActivityId);
setContentView(R.layout.demo);
resultFragment = (ResultFragment) getFragmentManager().findFragmentById(R.id.result_fragment);
getLoaderManager().initLoader(0, null, this);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("DemoActivity", "onDestroy for " + myActivityId);
}
#Override
public void onRowTapped(Integer number) {
selectedNumber = number;
resultFragment.setResultText("Fetching details for item " + number + "...");
getLoaderManager().restartLoader(0, null, this);
}
#Override
public Loader<String> onCreateLoader(int id, Bundle args) {
return new ResultLoader(this, selectedNumber);
}
#Override
public void onLoadFinished(Loader<String> loader, String data) {
Log.d("DemoActivity", "onLoadFinished reporting to activity " + myActivityId);
resultFragment.setResultText(data);
}
#Override
public void onLoaderReset(Loader<String> loader) {
}
static final class ResultLoader extends AsyncTaskLoader<String> {
private static final Random random = new Random();
private final Integer number;
private String result;
ResultLoader(Context context, Integer number) {
super(context);
this.number = number;
}
#Override
public String loadInBackground() {
// Simulate expensive Web call
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Item " + number + " - Price: $" + random.nextInt(500) + ".00, Number in stock: " + random.nextInt(10000);
}
#Override
public void deliverResult(String data) {
if (isReset()) {
// An async query came in while the loader is stopped
return;
}
result = data;
if (isStarted()) {
super.deliverResult(data);
}
}
#Override
protected void onStartLoading() {
if (result != null) {
deliverResult(result);
}
// Only do a load if we have a source to load from
if (number != null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
result = null;
}
}
}
List fragment:
public final class NumberListFragment extends ListFragment {
interface RowTappedListener {
void onRowTapped(Integer number);
}
private RowTappedListener rowTappedListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
rowTappedListener = (RowTappedListener) activity;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getActivity(),
R.layout.simple_list_item_1,
Arrays.asList(1, 2, 3, 4, 5, 6));
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
ArrayAdapter<Integer> adapter = (ArrayAdapter<Integer>) getListAdapter();
rowTappedListener.onRowTapped(adapter.getItem(position));
}
}
Result fragment:
public final class ResultFragment extends Fragment {
private TextView resultLabel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.result_fragment, container, false);
resultLabel = (TextView) root.findViewById(R.id.result_label);
if (savedInstanceState != null) {
resultLabel.setText(savedInstanceState.getString("labelText", ""));
}
return root;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("labelText", resultLabel.getText().toString());
}
void setResultText(String resultText) {
resultLabel.setText(resultText);
}
}
I've been able to get this working using plain AsyncTasks but I'm trying to learn more about Loaders since they handle the configuration changes automatically.
EDIT: I think I may have tracked down the issue by looking at the source for LoaderManager. When initLoader is called after the configuration change, the LoaderInfo object has its mCallbacks field updated with the new activity as the implementation of LoaderCallbacks, as I would expect.
public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
if (mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
LoaderInfo info = mLoaders.get(id);
if (DEBUG) Log.v(TAG, "initLoader in " + this + ": args=" + args);
if (info == null) {
// Loader doesn't already exist; create.
info = createAndInstallLoader(id, args, (LoaderManager.LoaderCallbacks<Object>)callback);
if (DEBUG) Log.v(TAG, " Created new loader " + info);
} else {
if (DEBUG) Log.v(TAG, " Re-using existing loader " + info);
info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
}
if (info.mHaveData && mStarted) {
// If the loader has already generated its data, report it now.
info.callOnLoadFinished(info.mLoader, info.mData);
}
return (Loader<D>)info.mLoader;
}
However, when there is a pending loader, the main LoaderInfo object also has an mPendingLoader field with a reference to a LoaderCallbacks as well, and this object is never updated with the new activity in the mCallbacks field. I would expect to see the code look like this instead:
// This line was already there
info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
// This line is not currently there
info.mPendingLoader.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
It appears to be because of this that the pending loader calls onLoadFinished on the old activity instance. If I breakpoint in this method and make the call that I feel is missing using the debugger, everything works as I expect.
The new question is: Have I found a bug, or is this the expected behavior?
In most cases you should just ignore such reports if Activity is already destroyed.
public void onLoadFinished(Loader<String> loader, String data) {
Log.d("DemoActivity", "onLoadFinished reporting to activity " + myActivityId);
if (isDestroyed()) {
Log.i("DemoActivity", "Activity already destroyed, report ignored: " + data);
return;
}
resultFragment.setResultText(data);
}
Also you should insert checking isDestroyed() in any inner classes. Runnable - is the most used case.
For example:
// UI thread
final Handler handler = new Handler();
Executor someExecutorService = ... ;
someExecutorService.execute(new Runnable() {
public void run() {
// some heavy operations
...
// notification to UI thread
handler.post(new Runnable() {
// this runnable can link to 'dead' activity or any outer instance
if (isDestroyed()) {
return;
}
// we are alive
onSomeHeavyOperationFinished();
});
}
});
But in such cases the best way is to avoid passing strong reference on Activity to another thread (AsynkTask, Loader, Executor, etc).
The most reliable solution is here:
// BackgroundExecutor.java
public class BackgroundExecutor {
private static final Executor instance = Executors.newSingleThreadExecutor();
public static void execute(Runnable command) {
instance.execute(command);
}
}
// MyActivity.java
public class MyActivity extends Activity {
// Some callback method from any button you want
public void onSomeButtonClicked() {
// Show toast or progress bar if needed
// Start your heavy operation
BackgroundExecutor.execute(new SomeHeavyOperation(this));
}
public void onSomeHeavyOperationFinished() {
if (isDestroyed()) {
return;
}
// Hide progress bar, update UI
}
}
// SomeHeavyOperation.java
public class SomeHeavyOperation implements Runnable {
private final WeakReference<MyActivity> ref;
public SomeHeavyOperation(MyActivity owner) {
// Unlike inner class we do not store strong reference to Activity here
this.ref = new WeakReference<MyActivity>(owner);
}
public void run() {
// Perform your heavy operation
// ...
// Done!
// It's time to notify Activity
final MyActivity owner = ref.get();
// Already died reference
if (owner == null) return;
// Perform notification in UI thread
owner.runOnUiThread(new Runnable() {
public void run() {
owner.onSomeHeavyOperationFinished();
}
});
}
}
Maybe not best solution but ...
This code restart loader every time, which is bad but only work around that works - if you want to used loader.
Loader l = getLoaderManager().getLoader(MY_LOADER);
if (l != null) {
getLoaderManager().restartLoader(MY_LOADER, null, this);
} else {
getLoaderManager().initLoader(MY_LOADER, null, this);
}
BTW. I am using Cursorloader ...
A possible solution is to start the AsyncTask in a custom singleton object and access the onFinished() result from the singleton within your Activity. Every time you rotate your screen, go onPause() or onResume(), the latest result will be used/accessed. If you still don't have a result in your singleton object, you know it is still busy or that you can relaunch the task.
Another approach is to work with a service bus like Otto, or to work with a Service.
Ok I'm trying to understand this excuse me if I misunderstood anything, but you are losing references to something when the device rotates.
Taking a stab...
would adding
android:configChanges="orientation|keyboardHidden|screenSize"
in your manifest for that activity fix your error? or prevent onLoadFinished() from saying the activity stopped?