0
The Problem
I’m developing an app that has a side navigation menu (Navigation Drawer
) as shown below.
Loading some items from this menu requires an Internet request. Here at this point everything works perfectly. When choosing the menu item with this feature I run an Asynctask that performs the request, retrieves and updates the information in the View. But if I choose another menu item without this Asynctask being finalized, a situation is created that invalidates all treatment performed in the Asynctask callback and results in application failure.
Faced with the problem reported above, I want to cancel the Asynctask execution when another menu option is chosen. How to implement this cancellation properly?
Implementation code of the mentioned 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);
}
}
}
Execution of the 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;
}
}
Piovezan, your solution is great! It worked perfectly. I decided not to give up the simplicities of the use of Listfragment and for this I dismembered a little its solution to meet my need, but in essence it is the same solution. I will post here to include and to be an alternative to those who want to continue using the listing with Listfragment.
– Geison Santos