java


Proper way to subclass a Java AsyncTask for looser coupling [duplicate]


I was wondering if AsyncTask was made to be used inside the main activity (MainActivity.java) running the thread.
For example I noticed many tutorials when using the AsyncTask they declare a private class inside the main class extending the Activity rather than creating an independent .java file for that AsyncTask (MyAsyncTask.java) class.
But I noticed that when using an independent file i'm not being able to run the runOnUIThread() because it belongs to the Activity class, so how will i be able to use this method inside that independent AsyncTask (MyAsyncTask.java) which extends AsyncTask and not Activity.
That is completely fine. I do it often but it depends on how you are using it. If it may be used by othe Activities then I give it it's own class or a shared class. But if it is for a single purpose then I would make it an inner class of the MainActivity.
The benefit of making it an inner class is that it has direct access to that classes member variables. If you make it a separate class then you just need to create a constructor for it if you need to pass in params such as a context or other variables.
I don't know exactly what you are doing but I'm not sure you need runOnUiThread(). You can create a constructor in your AsyncTask file and have it accept context as a param and whatever else you need. Then you can update the UI in onPostExecute()
Example
Public class MyAsyncTask extends AsyncTask
{
private Context context;
public MyAsyncTask(Context context) { // can take other params if needed
this.context = context;
}
// Add your AsyncTask methods and logic
//you can use your context variable in onPostExecute() to manipulate activity UI
}`
then call it in your MainActivity
MyAsyncTask myTask = new MyAsyncTask(this); //can pass other variables as needed
myTask.execute();
Yes You can create AsyncTask class in your MainActivity.java.
public class CategoryListScreen extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new loadcategory().execute();
}
class loadcategory extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { }
protected void onPostExecute(Void param) { }
} // AsyncTask over
}//main class over
Generally we place AsyncTask in same class to make it more clear that it is used by the same activity only.
If you want that AsyncTask tobe reused by more than one activity than, you can simply create an independent class and pass the parameters from activity by constructors
You can create interface in your asyncTask to send response from asynctask to your activity like below and call you lister method whenever required. I have called it onPostExecute():
public class DeckDownloader extends AsyncTask<Void, Void, String> {
OnDownloadUpdateListener listener;
public interface OnDownloadUpdateListener {
public void OnDownloadDeckFinish(String Response);
}
public DeckDownloader(Context ctx, OnDownloadUpdateListener listener) {
mContext = ctx;
this.listener = listener;
}
#Override
protected String doInBackground(Void... params) {
String str = "downloading";
//your async code goes here
return str;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
if( listener != null ) {
listener.OnDownloadDeckProgress(result);
}
}
}
And in Your Activity class, you need to implement that listener and write your code to update textview in that implementation method:
public class myActivity extends Activity{
private DeckDownloader.OnDownloadUpdateListener downloadListener;
TextView txtAsyncResponse;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txtAsyncResponse = (TextView) findViewById(R.id.txtAsyncResponse);
downloadListener = new DeckDownloader.OnDownloadUpdateListener() {
#Override
public void OnDownloadDeckFinish(String Response) {
txtAsyncResponse.setText(Response);
}
};
}
And you can write below code to start AsyncTask in your activity whenever required like button click event or else
DeckDownloader mTask = new DeckDownloader(this.getApplicationContext(), downloadListener);
mTask.execute();
This can be the thindg you want!
I believe in most tutorials they pick whatever is easiest to understand/read, not what is actually the best.
With an inner class, you keep your variables of the Activity available, which can be simpler.
In general, you should encapsulate as much as possible, also your AsyncTasks, so you can re-use them from any other point in your code.

Related Links

Blank ListView with BaseAdapter
SINGLE_INTERVAL_SELECTION is not working as expected
Java: Call a main method from a main method in another class
Runtime error when accessing other controller's element in Java/Scala
Prime number beetween 90 and 150
Best approach for creating a generic REST response for a database model
What is the most efficient way to find the image type(like jpeg,gif) from a multipart image file in java
Recursion: sum digits of a number until there is a single digit left
Translate odata URi string to HIbernate for MYSQL database
SVM OpenCV example questions
Sorting a collection in a generic method in Java 8
Android Parse Push Notification not working - “Outdated device”
Is it possible to get two output parameters from stored T-SQL procedure using Hibernate 4?
Multiple default values for collections with Jersey
Achieve behaviour same as AppBarLayout for any ViewGroup in CoordinatorLayout
Can we access hibernate session from separate deployed application?

Categories

HOME
ms-access
netsuite
server
heroku
analysis
rdf
twitter-bootstrap-4
jgroups
convolution
communication
percona
lombok
dosgi
libtiff
angular-ui
pugjs
propel
samoa
viewport
scichart
predix
mps
php-openssl
jndi
apache-commons-io
semantic-analysis
status
internet-explorer-9
jspm
tasklet
instant-messaging
skia
microsoft-chart-controls
exuberant-ctags
commit
http-referer
picasso
adobe-premiere
service-discovery
lumberjack
email-templates
pdf-reactor
node-gyp
isbn
flashair
reactive-cocoa-5
qcombobox
websphere-mq-fte
qwt
blogengine.net
rdfs
tactic
composite-key
namecoin
knpmenubundle
imanage
dwscript
redundancy
account-kit
vtigercrm
yt-project
messenger
ado.net-entity-data-model
django-debug-toolbar
lttng
prettytensor
ready-api
qgraphicsview
javax.sound.midi
iad
spim
intellij-14
wordml
fouc
pundit
tarjans-algorithm
drawbitmap
riak-cs
dereference
streambase
bridge.net
inmobi
apache-commons-net
relocation
rdl
bitcoinj
project-planning
system.net.webexception
poller
balanced-payments
prettify
gridfs
yui-compressor
type-equivalence
itmstransporter
browser-detection
hosts-file
getmessage
ohm
assembly-loading
fireworks
gwt-ext
nsobject
qt-jambi
pydot
data-loss
oncheckedchanged
android-sdk-2.1
zend-translate
gallio
dentrix
boost-smart-ptr
temporal-database
django-notification

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App