I’m in the process of setting up a background task that makes network calls; however, my development has stalled as a result of the fact that I am unable to get my AsyncTask that I have set up to work, what I did was I placed toasts at various points in the code to see where the problem was occurring. I realized that I would get a toasts at all points right up to the pre execute method of the AsyncTask; however, in the doInBackground and postexecute, I would get nothing.
Why is this? and if this can’t be done what is the work around?
package com.testapp2.second.activities;
import java.util.Date;
import com.testapp2.second.OTweetApplication;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.widget.Toast;
public class StatsCheckerService extends Service {
private OTweetApplication app;
private Twitter twitter;
User user;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
app = (OTweetApplication) getApplication();
twitter = app.getTwitter();
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (app.isAuthorized()) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG)
.show();
new toastTwitterInBg();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
private class toastTwitterInBg extends AsyncTask<Void, Void, User> {
@Override
protected User doInBackground(Void... arg0) {
try {
user = twitter.verifyCredentials();
Toast.makeText(StatsCheckerService.this, "async tasks do in background", Toast.LENGTH_LONG).show();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
@Override
protected void onPostExecute(User result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(StatsCheckerService.this, "async tasks on post execute finished", Toast.LENGTH_LONG).show();
}
}
}
As someone else already pointed out, toasts will not work in
doInBackgroundas that runs on a separate thread. Also, are you actually executing yourAsyncTask?Shouldn’t this be:
Note the
.execute().