android


Generic Asynctask for multiple activities


Hi I am trying to implement a generic Asynctask in android. I have around 8 to 10 activities which uses same asynctask with different parameters. Task works well for each activity. But when I try to implement a UI component it crashes. Here is my code any suggestions
public class SyncTaskService extends AsyncTask<String, Void, Void> {
OnAsyncResult onAsyncResult;
String ServerResponse;
String LocalResponse;
int Operationtype=-1;
private Context mContext;
public SyncTaskService (Context context){
mContext = context;
}
public void setOnResultListener(OnAsyncResult onAsyncResult) {
if (onAsyncResult != null) {
this.onAsyncResult = onAsyncResult;
}
}
#Override
protected Void doInBackground(String... params) {
BackGroundTasks Obj_BackGroungTasks = new BackGroundTasks();
Operationtype = Integer.parseInt(params[0]);
if (onAsyncResult != null)
{
switch (Operationtype) {
case 1:
String Type = params[2];
ServerResponse=null;
ServerResponse= Obj_BackGroungTasks.getdetails(mContext,Type);
break;
default:
break;
}
}
if (ServerResponse!=null) {
onAsyncResult.onResultSuccess(ServerResponse);
} else {
onAsyncResult.onResultFail(ServerResponse +LocalResponse);
}
return null;
}
public interface OnAsyncResult {
public abstract void onResultSuccess(String message);
public abstract void onResultFail(String errorMessage);
}
and this is how I am using it in my activity
SyncTaskService task = new SyncTaskService(getActivity());
task.setOnResultListener(asynResult);
task.execute("5",promotype);
OnAsyncResult asynResult = new OnAsyncResult() {
#Override
public void onResultFail(final String errorMessage) {
Log.d("On Result Fail In Activity", ""+errorMessage);
Toast.makeText(getActivity(), "Task completed", Toast.LENGTH_LONG).show();
}
#Override
public void onResultSuccess(String message) {
Log.d("On Result Success In Activity", ""+message);
ServerResponse=message;
Toast.makeText(getActivity(), "Task completed", Toast.LENGTH_LONG).show(); //craches here
}
};
Here us logcat
11-08 16:25:17.705: E/AndroidRuntime(671): FATAL EXCEPTION: AsyncTask #1
11-08 16:25:17.705: E/AndroidRuntime(671): java.lang.RuntimeException: An error occured while executing doInBackground()
11-08 16:25:17.705: E/AndroidRuntime(671): at android.os.AsyncTask$3.done(AsyncTask.java:278)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-08 16:25:17.705: E/AndroidRuntime(671): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.lang.Thread.run(Thread.java:856)
11-08 16:25:17.705: E/AndroidRuntime(671): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-08 16:25:17.705: E/AndroidRuntime(671): at android.os.Handler.<init>(Handler.java:121)
11-08 16:25:17.705: E/AndroidRuntime(671): at android.widget.Toast$TN.<init>(Toast.java:317)
11-08 16:25:17.705: E/AndroidRuntime(671): at android.widget.Toast.<init>(Toast.java:91)
11-08 16:25:17.705: E/AndroidRuntime(671): at android.widget.Toast.makeText(Toast.java:233)
11-08 16:25:17.705: E/AndroidRuntime(671): at packagename.Activity$1.onResultFail(Activity.java:157)
11-08 16:25:17.705: E/AndroidRuntime(671): at packagename.SyncTaskService.doInBackground(SyncTaskService.java:115)
11-08 16:25:17.705: E/AndroidRuntime(671): at packagename.SyncTaskService.doInBackground(SyncTaskService.java:1)
11-08 16:25:17.705: E/AndroidRuntime(671): at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-08 16:25:17.705: E/AndroidRuntime(671): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-08 16:25:17.705: E/AndroidRuntime(671): ... 5 more
You need to override onPostExecuted() method. Basically, Asynctask has 4 important methods, three of which execute on the UI thread and one which executes in a background asynchronous thread:
onPreExecute() - executed on the UI thread where you should do whatever you want on the UI before your background process is executed ex. show a progress bar
doInBackground() - executed on a background thread and this is where you should do whatever heavy task need to do off the UI thread so that your app doesn't crash or your UI doesn't hang ex. make an API call to download. REMEMBER THAT YOU CANNOT INTERACT WITH ANY UI ELEMENTS HERE! You can also publish progress from here ex. Return file size downloaded every 200kb so that your progress bar can update
onPostExecute() - executed on the UI thread where you should handle everything you want to do on the UI after your task has executed ex. dismiss progress bar and show result of downloading file
onProgressUpdate() - executed on the UI thread when ever doInBackground() publishes progress so that you can keep your user updated in case of a long background process ex. update your progress bar percentage here
Hope this helps. You might also want to look at the documentation which might help you further to understand the full capabilities of Asynctask.
http://developer.android.com/intl/zh-tw/reference/android/os/AsyncTask.html
Happy coding :)

Related Links

What is long polling and how to use it in android For Chat Project
Android compress video after selecting video from gallery
AlertDialog with user input shows NullPointerException when OK Button is clicked
Box2d is working wierd after changing andengine resolution
android geolocation not returning address and locality
How to enable deep-linking in WebView on Android app?
This method must return a result of type boolean - android options menu
Trouble Removing Whitespace in URL (Android Studio)
Getting location of Views in Android in double format
Add different view in every row of a ListView
How can multiple files be committed to git repository with c4droid?
Relative layout looks ok in Eclipse, but not on device
Images not found on devices
Android multiple URLConnections
Sample video chat from Quickblox not working in Android
Error when navigating away from a page with a map on Android, while the on-screen keyboard is visible

Categories

HOME
asp.net-web-api
pascal
alsa
rds
pearson-correlation
tvos
azure-container-service
jtextpane
angularfire2
octave
github-enterprise
emoji
xcodebuild
keytool
glyphicons
symfony-2.8
video-editing
jmp
nim
bourbon
selinux
poedit
inno-download-plugin
php-mysqlidb
draft-js-plugins
siri
slidetoggle
licensing
corenlp-server
scatter3d
complex-numbers
left-join
dsx-desktop
classcastexception
sql-delete
least-squares
video-capture
sim-toolkit
comparison-operators
contract
android-exoplayer
snapchat
double-click
sonarlint-eclipse
dotnet-httpclient
fclose
datamaps
podscms
magic-draw
modelsim
django-1.10
testrail
vcloud-director-rest-api
actor-platform
redbeard-ios
webjars
seek
nservicebus5
httpruntime.cache
concept-insights
atan2
inf
xenomai
jdi
pax-exam
slash
actionfilterattribute
gamekit
apache-spark-1.3
dbaccess
showdialog
crowd
entry-point
genymotion-call
angular-carousel
codeplex
decoupling
gae-quotas
android-audiorecord
dtmf
unit-of-work
tlf
actiondispatch
cascadingdropdown
alice
sqlclr
joomla3.1
android-loadermanager
xcode3.2
faye
subgraph
boost-signals
apache-whirr
isa-swizzling
apache-commons-dbutils
entitydatasource
rmdir
load-time
glui
cuda.net
complex-event-processing

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