The Problem
I'm developing an app that has a side navigation menu ( Navigation Drawer
) as shown in the figure below.
Uploading some items from this menu requires an Internet request. Here everything works perfectly. When the menu item with this characteristic is selected, I execute an AsyncTask that performs the request, retrieves and updates the information in the View. However, if I choose another menu item without this AsyncTask being finalized, a situation is created that invalidates all the AsyncTask callback handling and results in application failure.
In the face of the problem reported above, I want to cancel AsyncTask execution when another menu option is chosen. How to implement this cancellation properly?
Implementation code of the above items
Menu Implementation
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
...
public void onDrawerItemSelected(View view, int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FavoritosFragment();
title = getString(R.string.title_favoritos);
break;
case 2:
fragment = new ReclamacaoFragment();
title = getString(R.string.title_reclamacoes);
break;
case 3:
fragment = new ConfiguracoesFragment();
title = getString(R.string.title_configuracoes);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
}
}
Running AsyncTask
public class FavoritosFragment extends ListFragment {
public FavoritosFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
new LinhaFavoritaTask(this).execute();
return rootView;
}
}