-1

My problem is almost the same as this Stop AsyncTask in Fragments when Back Button is pressed

But I want to stop my AsyncTask when the back arrow is clicked. I have a code in stoping asynctask and it works when I implemented it in another way. I tried what I researched so far but I still got errors. Please help me with this.

I tried this code

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    int id=item.getItemId();

    if(id==android.R.id.home)
    {
        Intent returnIntent = new Intent();
        returnIntent.putExtra("flag",userid);
        setResult(Activity.RESULT_OK,returnIntent);
        finish();
        return true;
    }}

UPDATED: I am using this code to go to another fragment.

Fragment2 fragmentChild = new Fragment2 ();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.content, fragmentChild);
transaction.addToBackStack(null);
transaction.commit();

I have no problem in my backtrack when I go to another fragment. Then I'm using this code (getSupportActionBar().setDisplayHomeAsUpEnabled(true)) in my (Drawer.java) to show the back arrow. Now I want to add event when I clicked back arrow.

EDIT: (Drawer.java)

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    final View.OnClickListener originalToolbarListener = toggle.getToolbarNavigationClickListener();

    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                toggle.setDrawerIndicatorEnabled(false);
                toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getSupportFragmentManager().popBackStack();
                    }
                });
            } else {
                toggle.setDrawerIndicatorEnabled(true);
                toggle.setToolbarNavigationClickListener(originalToolbarListener);
            }
        }
    });
Community
  • 1
  • 1
Yhajiks
  • 115
  • 1
  • 12
  • 1
    What errors did you get? – jayeshsolanki93 May 16 '17 at 10:33
  • The errors when AsyncTask didn't work. I tried that code above, it works when I using an Activity. But I am using a fragment – Yhajiks May 17 '17 at 02:00
  • @Benjie show your LogCat or those "errors". – Sufian May 17 '17 at 06:51
  • @Sufian it's like this "[DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL" or sometimes "Can't locate view of my fragment". Sorry I can't give the whole logcat error because I can't find the previous ones. The error happened when my AsyncTask didn't finish yet loading the data from server to my listview then I pressed back – Yhajiks May 17 '17 at 07:15
  • @Benjie update your question and paste this LogCat there. Also please format it. – Sufian May 17 '17 at 07:19
  • This question now appears a duplicate of http://stackoverflow.com/questions/14437745/how-to-override-action-bar-back-button-in-android – Sufian May 17 '17 at 09:34
  • it still doesn't solve my problem. It's like android.R.id.home is not working – Yhajiks May 17 '17 at 09:50
  • Let's make it clear once for all: by using `error` you mean that your code is compiling, but not running as expected? Or your code doesn't compile at all and you have some compilation errors? – Iulian Popescu May 17 '17 at 10:10
  • My code is running, and I only encounter error when I clicked back even asynctask is not yet complete. Sorry – Yhajiks May 17 '17 at 10:27
  • @Benjie please use write `@sufian` in your comment if you want me to get notification (so I know I need to respond). – Sufian May 18 '17 at 08:11
  • @Benjie you didn't state what didn't work in regards to `android.R.id.home`. Give more detail. – Sufian May 18 '17 at 08:13
  • @Sufian it's not detecting any event. I tried adding toast but it didn't work. Btw, I am using fragment sir – Yhajiks May 19 '17 at 02:45
  • @Benjie in Fragments, you have to write `setHasOptions(true);` in your `onActivityCreated()` (or related method) of your Fragment. Only after this, you can inflate the menu or have `onOptionsItemSelected()` of your Fragment called. – Sufian May 19 '17 at 09:49

1 Answers1

0

If you properly setup the action bar, then you should be able to achive that with the following:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // Add the code to stop the task
        break;
    }
    return super.onOptionsItemSelected(item);
}

EDIT: After you are able to handle the back button event, you can add the code to close the tasks in fragments. First of all, I created an interface that is implement by all fragments that should be able to close this tasks.

public interface TaskCancelFragment {
    void cancelTask();
}

The implementation in fragments should look something like this:

@Override
public void cancelTask() {
    //Add the code to cancel the task
    Toast.makeText(getContext(), "The task is canceled", Toast.LENGTH_SHORT).show();
}

The final step is to send the event from activity to fragment. Here I will assume some things since I don't have access to your code to see how you add/find the fragments, but fortunately this doesn't matter so much and is easy to change. In addition to the initial answer, I created a new method in activity to find the current fragment and close the task.

private void cancelTasks() {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.placeholder);
    if (fragment instanceof TaskCancelFragment) {
        ((TaskCancelFragment) fragment).cancelTask();
    }
}

And in the end, the case android.R.id.home looks like this:

case android.R.id.home:
    cancelTasks();
    onBackPressed(); // I think that you want to close the activity too
    break;
Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
  • I am using this getSupportActionBar().setDisplayHomeAsUpEnabled(true) to show arrow back when I click another fragment. I tried using that code in an Activity and it works fine, is it also applicable in a Fragment? – Yhajiks May 17 '17 at 02:02
  • No, this will not work in a Fragment by itself. To make it work you will have to create a small workaround. – Iulian Popescu May 17 '17 at 06:21
  • can you please give me an example on how to do it? – Yhajiks May 17 '17 at 06:55
  • I updated the answer to handle the task closing inside fragments. Leave a comment if something is unclear. – Iulian Popescu May 17 '17 at 07:57
  • Thank You for the response. I think my problem is that it can't still detect when back arrow is clicked. And I used the code you post. I updated my question for more info – Yhajiks May 17 '17 at 09:15
  • Add the code for activity where you add the action bar, because if you don't receive the event, the problem is surely there. – Iulian Popescu May 17 '17 at 09:19
  • I really don't know where the error is. Im still new in android dev.. I put the code of my drawer above. Btw, I only change the hamburger nav to back arrow. Thank You – Yhajiks May 17 '17 at 10:04