Cancel Asynctask in android. How to cancel and handle asynctask in android and handle it

useful video : https://youtu.be/7vM-y8v0pro

Step 1 ] Take the Asynctask object whihc executed the task and apply it a cancel() method.

Step2]  Put an 'if ' condition inside the doInbackground() method to check if the task is cancelled and handle it as followed.


Step3] use suitable Cancellation method from the 2 oncancel() method to handle whatbhappens after the task is cancelled. WE CAN ALSO UPDATE THE UI from these methods.





Full code :


public class MainActivity extends AppCompatActivity {
NestedClass nestedClass;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void StartMethod(View view) {

nestedClass = new NestedClass();
nestedClass.execute();

}

public void Cancelmethod(View view) {
nestedClass.cancel(true);
}

class NestedClass extends AsyncTask<String,String,String>{

@Override
protected String doInBackground(String... strings) {
for (int i=0;i<10;i++){
if (isCancelled()){
Log.d("Keyy","Task is cancelled !");
//break is very imp since the propgram will
// come out if the tasked is cancelled.
break;
}else{
Log.d("Keyy","Counter no : " + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//This data is passed to the Cancel method() for Data handling
return null;
}

//Call this one if you dont want to handle any Data after Thread cancellation
@Override
protected void onCancelled() {
TextView textView = findViewById(R.id.textview_display);
textView.setText(" Program cancelled");
}

//Call this one if you WANT to handle any Data after Thread cancellation
//It takes Data returned from the doInBackground() method
@Override
protected void onCancelled(String s) {
TextView textView = findViewById(R.id.textview_display);
textView.setText(" Program cancelled with Data " + s);
}
}

}

Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)