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

Android: is this image/page indicator a standard widget?
Android application installation [closed]
How i can get Ice Cream Sandwich Layout like?
Eclipse Indigo plug-in Error: “org.eclipse.jface”
Saving listview content to sd-card in android
Jersey Client on Android - NullPointerException
css editor “Could not open the editor: Argument not valid”
AlertDialog.Builder open another AlertDialog.Builder
Android notification in AlarmReceiver
Passing data between a fragment and its container activity
How to get the little indicator triangle to custom action in ActionBar?
Android and Eclipse: Sticky debug mode
How to get value of only one Element from an Xml file using XmlResourceParser on Android?
Use of onTouchEvent in GestureDetector
activity call throws error
How To Create a “Package Private” Android Application?

Categories

HOME
android
asp.net-web-api
facebook-oauth
adal
hyperlink
checkstyle
cheerio
ggplot2
dns
object
pyqt
yahoo-finance
tivoli
square
mvc5
discrete-mathematics
drop-down-menu
fhir
text-mining
windows-ce
project-intu
alamofire
jsonpath
atlassian
parameter-passing
alpacajs
kendo-mobile
question2answer
jquery-callback
dapper-extensions
siri
surveymonkey
underscore.js
quantlib
userdefaults
cognos-bi
dsx-desktop
indy10
servicestack-text
video-capture
magento-1.9.2.4
docfx
sql-server-ce
android-augmented-reality
ogc
odoo-website
sharp-snmp
microsoft-metro
angular-http
android-checkbox
file-sharing
jide
lampp
builder
chai-as-promised
insight
singleinstance
ngmaterial
deep
tracker-enabled-dbcontext
query-by-example
cortex-m
ellucian-scribe
jbase
dynamics-nav-2016
qt5.2
themoviedb-api
computer-architecture
jdi
dock
iced-coffeescript
avahi
ms-access-2000
code-documentation
procedural-programming
grouping-sets
variadic-templates
dbaccess
android-cookiemanager
addressing-mode
crowd
device-tree
raygun
encryption-asymmetric
lnk
renderer
extjs2
sbcl
syndicationfeed
windows-embedded-standard
high-resolution
cffile
gpars
nebula
dolby-audio-api
pclzip
database-create
urlrewriter
gobject-introspection
entity-attribute-value
winmain
tmx
rowlex
feasibility
wordprocessingml
int64

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