Please share how to use intent in doinbackground() or onpostexecute() methods Asynctask class.When I tried to use these codes it shows error.
Intent intent = new Intent(asynctask.this, home.class);
startActivity(intent);
finish();
private Class<Home> clazz;
public asynctask(Class<Home> clazz){
this.clazz = clazz;
}
Asynctask doInBackground() method:
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, clazz);
startActivity(intent);
finish();
Toast.makeText(cxt, "welcome", Toast.LENGTH_SHORT).show();
return null;
}
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Asynchronous tasks are divided into three generic types: Params, Progress, & Result and four steps: onPreExecute, doInBackground, onProgressUpdate, & onPostExecute.
Why Android AsyncTask is Deprecated? Here is the official reason it is deprecated. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.
Try this way,hope this will help you to solve your problem.
How to asynctask class :
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyCustomAsyncTask(this).execute();
}
MyCustomAsyncTask.java
public class MyCustomAsyncTask extends AsyncTask<Void,Void,Void> {
private Context context;
public MyCustomAsyncTask(Context context){
this.context=context;
}
@Override
protected void onPreExecute() {
// write show progress Dialog code here
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// write service code here
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(context, "welcome", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, home.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
Move this Intent part in onPostExecute(...)
method of AsynckTask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With