2

I have a list of items on which user can click for download. For which I am having this code:

//Maintained this in my ListAdapter class so that if user clicks on cancel download i can do:
// tasks.get(info.getFieldID()).cancel(true);

public static Map<String, Future<Object>> tasks = new HashMap<String, Future<Object>>();
    Future f = downloadExecutor.submit(new Callable<Object>() {
         // do downloading.
    }
    tasks.put(key,f);

I am trying to cancel this the respective download when user clicks on cancel by calling tasks.get(key).cancel(true);

But my task is not getting cancelled.

Few questions:

  1. Am I doing anything wrong by maintaining the list of future objects in the adapter class ?

  2. How should i get a task to get cancelled when user clicks on a button?

  3. Also how do i know that the task has been cancelled?

I have read about ExecutorService but I am little confused about the implementation.

user2234
  • 1,282
  • 1
  • 21
  • 44
  • This is definitely a duplicate question, the answer is to put some nasty volatile Boolean flag in your processing loop somewhere, and check if the job should be canceled or not. Note it is not clear if you want to cancel the task before it is executed or while it is executing. – Derrops Sep 14 '15 at 14:06

1 Answers1

0

You are really asking several questions together. The logic behind your problem appears to be connecting a physical action (button press) with an executable action (cancel task).

In simple terms, you seem to recognize the need to store a reference to the task in order to cancel it. In pseudocode (because your particular implementation may differ), you want something like:

Button myButton = (Button)findViewById(R.id.mybutton);
myButton.setOnClickListener(new OnClickListener() {
    @Override
    onClick(View v) {
        tasks
             // retrieve the proper task based on the button
             .get(oneKey)
             // once you have the task, cancel it
             .cancel(true);
    }
});

In the code above, each button will be associated with whichever task you choose, which you can do through hard-coding or passing variables.

Using the hashtable, retrieve the task you want. Then use its cancel method to cancel it.

Jim
  • 10,172
  • 1
  • 27
  • 36
  • Sorry for so many questions! but I am little confused. I have done the same for cancelling it on a button click, but the task is not getting cancelled. I also tried solutions mentioned on other posts, but neither worked! – user2234 Sep 14 '15 at 14:13
  • OK - then you need to post code and ask a more specific question about a single approach. If you do not have a general question, please do not ask a general question. Since you have written code, post it and ask specific questions about it. – Jim Sep 14 '15 at 14:15