android


Android: How to call non static method of an activity from AsyncTask (via doInBackground)


I have a class that takes care of performing background tasks.
public class BackgroundTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog dialog;
public BackgroundTask(AppCompatActivity activity)
{
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Doing something, please wait.");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
}
#Override
protected void onPostExecute(Void result)
{
if (dialog.isShowing())
{
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params)
{
try
{
// How can I call non-static method of MyActivity here?
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
}
In my activity MyActivity (derived from AppCompatActivity) whenever there are time consuming task, I call it like this:
BackgroundTask task = new BackgroundTask(MyActivity.this);
task.execute();
And then displays waiting animation in dialog which is perfectly fine. I like to know: How can I pass non static method (that consumes time) which belongs to MyActivity (and any other activities) to this BackgroundTask so that I can call it from `doInBackground' ?
Thanks in advance.
public class BackgroundTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private MyActivity activity;
public BackgroundTask(MyActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
...
#Override
protected Void doInBackground(Void... params) {
try {
activity.callWhatYouNeed();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
But take care about what you call inside doInBackground, becasue this method executes on non-main thread, so you can't do anything with Views. If you need do something with views, make call like this
public class BackgroundTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private MyActivity activity;
private Handler uiHandler;
public BackgroundTask(MyActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
uiHandler = new Handler(Looper.getMainLooper());
}
...
#Override
protected Void doInBackground(Void... params) {
try {
mHandler.post(new Runnable() {
#Override
public void run() {
activity.callWhatYouNeed();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
UPDATE: if you want use AsyncTask with other activities, you should use inheritance and create one BaseActivity with callWhatYouNeed()
public abstract class BaseActivity extends AppCompatActivity {
public abstract void callWhatYouNeed();
}
extends from BaseActivity:
public class MyActivity extends BaseActivity {
#Override
public void callWhatYouNeed() {
//Implementation
}
}
and change AsyncTask
public class BackgroundTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog dialog;
private BaseActivity activity;
public BackgroundTask(BaseActivity activity)
{
this.activity = activity;
dialog = new ProgressDialog(activity);
}
#Override
protected Void doInBackground(Void... params) {
try {
activity.callWhatYouNeed();
}
catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
Or you can check activity with instanceof operator:
public class BackgroundTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private AppCompatActivity activity;
public BackgroundTask(AppCompatActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
...
#Override
protected Void doInBackground(Void... params){
try {
if (activity instanceof MyActivity) {
((MyActivity) activity).callWhatYouNeed();
} else if (acitivty instanceof SeocndActivity) {
((SecondActivity) activity).secondCall();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
But it is bad practice to use instanceof, so i strongly recommend use inheritance.
BackgroundTask task = new BackgroundTask(MyActivity.this);
task.execute();
When you call above code in MyActivity class at that time You have passed the instance on class in a constructer. So You can get any non-static method from MyActivity class. for example
public class BackgroundTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog dialog;
private MyActivity activity;
public BackgroundTask(MyActivity activity)
{
this.activity = activity;
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Doing something, please wait.");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
}
#Override
protected void onPostExecute(Void result)
{
if (dialog.isShowing())
{
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params)
{
try
{
activity.callyourmethod();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
}

Related Links

How to remove white border from imageView while using Display Metrics?
Clear EditText value in a RecyclerView row
Error with import android.support.annotation.NonNull
Transparncy GIF for android app
Manifest merger failed with multiple errors, see logs and cannot build a project
How to set BitmapFactory.Option to bitmap object?
Multiple recyclerview issue
Ionic2 how to enable mapTypeControl in google map
“ApplicationDT” has been stopped
Passing a native fd int to FFMPEG from openable URI
How to add a EditText in circle shape and accept only 1 number
Android - get userName whit user and pass to another activity [duplicate]
Android and Firebase Database: can I take new item whit query when I reach the end of the RecyclerView?
Android = TelephonyManager (Intent.ACTION_CALL)
How to add margin start to DividerItemDecoration Android
Android studio/AdMob/Firebase leave banner for premium

Categories

HOME
batch-file
youtube-data-api-v3
grafana
opendj
emscripten
3d-reconstruction
tail
python-multithreading
vert.x
joomla3.0
fosrestbundle
fabric.io
php-5.6
onedrive-api
do-while
glyphicons
atlassian-stash
vuejs
google-picker
google-container-registry
nodemcu
microsoft-ocr
aggregation
tosca
fat
custom-post-type
has-and-belongs-to-many
firebase-analytics
gp
livelink
dst
weather
jmockit
hibernate-validator
memory-address
rselenium
jett
classcastexception
searchkit
swagger-php
spring-mvc-test
vmware-fusion
skylink
android-ibeacon
chronicle-map
apache-directory
lampp
builder
cnc
launchctl
x-ray
aquamacs
wpas
context-sensitive-grammar
boxing
libjpeg
py2neo
rxtx
node-request
qtplugin
adafruit
jclouds
udpclient
ikiwiki
upx
thread-sleep
exim4
boomerang
toran-proxy
sciruby
wiredep
phonertc
pyobjc
user-permissions
public-html
cross-join
primitive-types
device-tree
encryption-asymmetric
lambda-architecture
ss7
jjaql
http-patch
facebook-timeline
dolby-audio-api
superscrollorama
extreme-programming
midlet
iboutlet
failing-tests
jquery-tools
drawtobitmap
easyb
opml
tui
cuda.net
google-wave
asynchronous-wcf-call

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App