How to let Async Task finish in Android - java

I'm working on an app that retrieves data from network, stores them to the device and then reads them.
Problem is, I get my data in a Async Task.. And my app doesn't let the task finish before trying to show the data to the user..
I've tried task.get() but without result (it just stops there).
Here is my task:
public GetOptionsTask(XMLPortalGetOptions request) {
super(request);
}
protected void onCancelled(){
// TODO afficher message pas d'options sur le disque
}
#Override
public void handleError(Transaction transaction) {
// TODO afficher message pas d'options sur le disque
}
#Override
public void handleSuccess(Transaction transaction) {
saveOptions(transaction.getResponse());
request = null;
Log.d(OptionsManager.class.getName(), this.getStatus().toString());
}
This task is an instance of my custom Async Task:
protected BaseXMLTransaction request;
public abstract void handleError(Transaction transaction);
public abstract void handleSuccess(Transaction transaction);
public TransactionTask(BaseXMLTransaction request){
this.request = request;
}
#Override
protected Void doInBackground(Void... params) {
try {
Log.i(TransactionTask.class.getName(), "Doing in background");
SocketHandler.sendTransaction(this, request.getRequest());
} catch (SocketHandlerNotConfiguredException e) {
Log.e(TransactionTask.class.getName(), "SocketHandler's parameters were not set.");
}
return null;
}
#Override
public void transactionResult(Transaction transaction) {
switch (transaction.getCode()) {
case ERROR:
Log.e(TransactionTask.class.getName(), "ERROR !!!");
handleError(transaction);
break;
case NO_CLIENT:
Log.e(TransactionTask.class.getName(), "No Client Error");
handleError(transaction);
break;
case NO_SERVER:
Log.e(TransactionTask.class.getName(), "No Server Error");
handleError(transaction);
break;
case OLD_VERSION:
Log.e(TransactionTask.class.getName(), "Old Version");
handleError(transaction);
break;
case TIMEOUT:
Log.e(TransactionTask.class.getName(), "Transaction Timeout");
handleError(transaction);
break;
case SUCCESS:
Log.i(TransactionTask.class.getName(), "Transaction Success");
handleSuccess(transaction);
}
}
I seriously don't know what to do... Execute goes to fast and get doesn't do anything since I'm not returning anything I guess.

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
#Override
protected void onPostExecute(String result) {
}

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
and call it like this:
new DownloadFilesTask().execute(url1, url2, url3);

I use an interface as a delegate to do this. Here is an example:
In my main activity I have a onClick listener to trigger my async call and a listener to process once the call is complete.
private void enableLocationButton(){
locationButton = (Button) findViewById(R.id.locationButton);
locationButton.setEnabled(true);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, selectLocationActivity.class);
intent.putExtra("serverURL",server.getWebServerAddressField());
startActivityForResult(intent, 200);
}
});
}
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(resultCode == RESULT_OK) {
switch (requestCode){
case 100:
processServerResponse((PmsWebServer) data.getBundleExtra("server").get("server"));
break;
case 200:
processLocationResponse((PmsDataSource)data.getBundleExtra("location").get("location"));
default:processError();
}
}else{
processError();
}
}
Somewhere in the selectLocationActivity I have a call to the Async call and something to process the response, please note that this class implements an interface that is used in the Async call.
public class selectLocationActivity extends ListActivity implements SoapServiceInterface{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_select);
chosenServer = this.removeURLHeader(getIntent().getStringExtra("serverURL"));
this.retrieveLocationOptionsByServer(chosenServer);
}
private void retrieveLocationOptionsByServer(String server) {
Map<String,Object> parms = new HashMap<String,Object>();
parms.put(WEB_SERVER_NAME,server);
SoapServiceObject service = new SoapServiceObject(Services.SERVICE_DETAILS,parms);
callTheService(service);
}
private void callTheService(SoapServiceObject service){
SoapServiceHelper helper = new SoapServiceHelper();
helper.delegate = thisActivity;
helper.execute(service);
}
#Override
public void serviceCallComplete(SoapObject response){
this.createClickableListOnScreen(response);
}
//...more code...//
}
serviceCallComplete is kicked off by the asyncTask. Below is the code for that task
public class SoapServiceHelper extends AsyncTask<SoapServiceObject, Void, SoapObject>{
public SoapServiceInterface delegate = null;
private Integer RETRY_COUNT = 0;
private final Integer MAX_RETRY_COUNT = 2;
protected SoapObject doInBackground(SoapServiceObject... args){
SoapServiceObject service = args[0];
try{
service.callTheService();
}catch(Exception e){
System.out.println("An error occurred calling the service\n" + e.getMessage());
}
return service.getResponse();
//return callDateTimeService();
}
protected void onPostExecute(SoapObject result){
delegate.serviceCallComplete((SoapObject)(result.getProperty(0)));
}
}
And finally here is the interface
public interface SoapServiceInterface {
public void serviceCallComplete(SoapObject response);
}
I know I'm displaying something to the screen directly from my result, just sub that part with a save and read ;)

One thing with that task was that it was saving stuff into a singleton. I managed to call the methods using the information from the network saved in the singleton at the onResume(). When the threads end, it goes to the onResume and everything works fine!

Related

Calling Volley from another class

I have an Activity class with quite a lot web services running and want to make my program more "object oriented",so it can be maintainable and easy to read . For example look at the following example.
public class Welcome extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_sample);
buildFitnessClient();
showUser(username,password);
}
private void buildFitnessClient() {
// Create the Google API Client
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs. What to do?
// Look at some data!!
//showUser(username,password);
new InsertAndVerifyDataTask().execute();
}
#Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG, "Connection lost. Reason: Service Disconnected");
}
}
}
)
.addOnConnectionFailedListener(
new GoogleApiClient.OnConnectionFailedListener() {
// Called whenever the API client fails to connect.
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed. Cause: " + result.toString());
if (!result.hasResolution()) {
// Show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
Welcome.this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization dialog is displayed to the user.
if (!authInProgress) {
try {
Log.i(TAG, "Attempting to resolve failed connection");
authInProgress = true;
result.startResolutionForResult(Welcome.this,
REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG,
"Exception while starting resolution activity", e);
}
}
}
}
)
.build();
}
#Override
protected void onStart() {
super.onStart();
// Connect to the Fitness API
Log.i(TAG, "Connecting...");
mClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mClient.isConnected()) {
mClient.disconnect();
//showUser(username,password);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
//showUser(username,password);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mClient.isConnecting() && !mClient.isConnected()) {
mClient.connect();
}
}
}
}
private void showUser(final String username, final String password) {
HttpsTrustManager.allowAllSSL();
String tag_json_obj = "json_obj_req";
location = getResources().getConfiguration().locale.getCountry();
final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("username", username);
postParams.put("password", password);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
//{"password":"larissa","username":"samsungtest"}
//{"password":"larissa","username":"theo81developer#gmail.com"}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_USER_CHECK, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// {"message":"User Information found.","user":{"username":"samsungtest","league_points":null,"team_id":"189","location":"GB","latest_steps":"0","user_type":"LEADER","nickname":"samsungtest"},"status":"success"}
//{"message":"User Information found.","user":{"username":"theo81developer#gmail.com","league_points":null,"team_id":"228","location":"GB","latest_steps":"5033","user_type":"LEADER","nickname":"Samsung User"},"status":"success"}
Log.d("TAG", response.toString());
try {
if (response.getString("status").equals("success")){
userTable(response);
localRanking(username,password,location);
globalRanking(username,password);
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
How can I make it work if I was calling buildFitnessClient() and showUser(...) from another class? I tried some different ways like instastiating a Class called Fitness with buildFitnessClient() method inside,but I am getting null pointer exception on View objects.
You can implement your methods as static so that you can call them from another class or activity and simply pass the required parameters that it may need (such as context, views, etc). And simply use them as something like Fitness.buildFitnessClient( < variables > )
OR
Implement a singleton where you can set variables to be used by your methods and do what you want to do. This, however, is much more complex (at least for me)
** Just be careful with memory leaks **

unable to post game score on facebook wall in android using libgdx framework

I am just trying to make a game where I need to post game score on facebook wall. And I am following libGDX framework. Below is my test activity that just post my custom message on facebook wall.
public class MainActivity extends Activity {
private static final String FB_APP_ID = "1452723631660564";
private static final String FACEBOOK_PERMISSION = "publish_stream";
private static final int FB_AUTH = 2; // ANY INTEGER VALUE
Facebook facebook = new Facebook(FB_APP_ID); //
static String FACEBOOK_UPDATE_MSG;
static String FACEBOOK_UPDATE_FAILURE;
static String FACEBOOK_UPDATE_SUCCESS;
static String FACEBOOK_SIGNIN_FAILED;
Handler fHandler = new Handler();
Map<Object, Object> preferences = new HashMap<Object, Object>();
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
login("Hello facebook test app");
}
#SuppressWarnings("deprecation")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FB_AUTH:
facebook.authorizeCallback(requestCode, resultCode, data);
break;
default:
finish();
break;
}
}
public void postMessageOnWall(final String msg) {
try {
if (facebook.isSessionValid()) {
new Thread(new Runnable() {
#Override
public void run() {
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("link", "ANDROID_MARKET_LINK"); // or any other
// link
parameters.putString("name", "APP/GAME NAME");
try {
#SuppressWarnings("deprecation")
String response = facebook.request("me/feed", parameters,
"POST");
FACEBOOK_UPDATE_MSG = FACEBOOK_UPDATE_SUCCESS;
fHandler.post(mUpdateFacebookNotification);
} catch (IOException e) {
FACEBOOK_UPDATE_MSG = FACEBOOK_UPDATE_FAILURE;
fHandler.post(mUpdateFacebookNotification);
}
}
});
}
} catch (Exception e) {
Log.e("error-----------", e.getLocalizedMessage());
}
}
final Runnable mUpdateFacebookNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), FACEBOOK_UPDATE_MSG,
Toast.LENGTH_LONG).show();
}
};
#SuppressWarnings("deprecation")
public void login(final String msg) {
/*String access_token = preferences.getString("facebook_access_token",
null);*/
String access_token = (String) preferences.get("facebook_access_token");
long expires = 0;
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(10000000l);
}
/*
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "publish_stream","read_stream", "offline_access" },
FB_AUTH, new DialogListener() {
#Override
public void onComplete(Bundle values) {
/*preferences.putString("access_token",
facebook.getAccessToken());
preferences.putLong("access_expires",
facebook.getAccessExpires());
preferences.flush();*/
preferences.put("access_token", facebook.getAccessToken());
preferences.put("access_expires", facebook.getAccessExpires());
if (msg != "")
postMessageOnWall(msg);
else
OpenFbPage();
}
private void OpenFbPage() {
}
#Override
public void onFacebookError(FacebookError error) {
FACEBOOK_UPDATE_MSG = FACEBOOK_SIGNIN_FAILED;
fHandler.post(mUpdateFacebookNotification);
}
#Override
public void onError(DialogError e) {
FACEBOOK_UPDATE_MSG = FACEBOOK_SIGNIN_FAILED;
fHandler.post(mUpdateFacebookNotification);
}
#Override
public void onCancel() {
}
});
}
}
}
I am not getting any exception/error in above code, but it also doesn't post my custom message on my facebook wall. It just opens an fb application and loading alert over that, nothing else. When I debug that, it neither reach on thread's run() method of postMessageOnWall() , nor I get any response defined in same method.
Please guide me where I am wrong. I know I write my whole code related to facebook post in single activity, but it just an test application. Once it is successful, I will segregate the logic.
among hundreds of things badly wrong with this example, you are not starting the thread (by calling start). If you had actually tried to make a small, self-contained example, as you should have, you would have found out on your own.

SpeechRecognitionService with word recognition

The title it's not clear i think. In my project i want a service that runs in background and when the user says "hello phone" or some word/phrase my app starts to recognize the voice. Actually it "works" but not in right way... I have a service and this service detect the voice.
public class SpeechActivationService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static String TAG = "Icaro";
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
private int mBindFlag;
private Messenger mServiceMessenger;
#Override
public void onCreate()
{
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
protected static class IncomingHandler extends Handler
{
private WeakReference<SpeechActivationService> mtarget;
IncomingHandler(SpeechActivationService target)
{
mtarget = new WeakReference<SpeechActivationService>(target);
}
#Override
public void handleMessage(Message msg)
{
final SpeechActivationService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d(TAG, "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d(TAG, "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
try
{
Message msg = new Message();
msg.what = MSG_RECOGNIZER_START_LISTENING;
mServerMessenger.send(msg);
}
catch (RemoteException e)
{
}
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer)
{
String sTest = "";
}
#Override
public void onEndOfSpeech()
{
Log.d("TESTING: SPEECH SERVICE", "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mIsListening = false;
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("TESTING: SPEECH SERVICE", "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Log.d(TAG, (String) data.get(0));
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "onResults"); //$NON-NLS-1$
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And i start service in my MainActivity just to try:
Intent i = new Intent(context, SpeechActivationService.class);
startService(i);
It detect the voice input...and TOO MUCH!!! Every time it detects something it's a "bipbip". Too many bips!! It's frustrating.. I only want that it starts when i say "hello phone" or "start" or a specific word!! I try to look at this https://github.com/gast-lib/gast-lib/blob/master/library/src/root/gast/speech/activation/WordActivator.java but really i don't know how use this library. I try see this question onCreate of android service not called but i not understand exactly what i have to do.. Anyway, i already import the gast library.. I only need to know how use it. Anyone can help me step by step? Thanks
Use setStreamSolo(AudioManager.STREAM_VOICE_CALL, true) instead of setStreamMute. Remember to add setStreamSolo(AudioManager.STREAM_VOICE_CALL, false) in case MSG_RECOGNIZER_CANCEL

AsyncTask on Android stops working after 2-5 minutes

Currently building an Android app and checking it on Genymotion running 4.1.1. I'm using AsyncTask to call the Bing Translate API to translate from text:
class TranslateFacebookText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... message) {
String translatedText = "";
try {
translatedText = Translate.execute(message[0], Language.AUTO_DETECT, Language.ENGLISH);
} catch (Exception e) {
....
}
return translatedText;
}
#Override
protected void onPostExecute(String translatedText) {
message = translatedText;
confirmTTSData();
}
}
public void onClick(View src) {
TranslateFacebookText translateTask = new TranslateFacebookText();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
translateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, message);
}
else {
translateTask.execute(message);
}
}
I'm using this method to start the task after reading this question: Android SDK AsyncTask doInBackground not running (subclass)
I'm doing so, since after about 2-5 minutes from the programs start, the AsyncTask refuses to run. That is, doInBackground does not get called, nor does onPostExecute. the onClick DOES get called, creates the new AsyncTask and runs the execution code, but the doInBackground does not get called.
This is completely random. I'm not doing anything else - just waiting there for a couple of minutes, and afterwards clicking the button again to see this happen. This is also true with a service which runs every specified time using a Handler and postDelayed. Here's an example:
public class MyService extends Service {
private Handler periodicEventHandler;
private final int PERIODIC_EVENT_TIMEOUT = 600000;
#Override
public void onCreate() {
periodicEventHandler = new Handler();
periodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
}
private Runnable doPeriodicTask = new Runnable()
{
public void run()
{
TranslateFacebookText translateTask = new TranslateFacebookText();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
translateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, message);
}
else {
translateTask.execute(message);
}
periodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
}
};
class TranslateFacebookText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... message) {
String translatedText = "";
try {
translatedText = Translate.execute(message[0], Language.AUTO_DETECT, Language.ENGLISH);
} catch (Exception e) {
....
}
return translatedText;
}
#Override
protected void onPostExecute(String translatedText) {
message = translatedText;
confirmTTSData();
}
}
}
The doPeriodicTask runs fine, again creating the AsyncTask and calling the execution code, but doInBackground never gets called. If I change PERIODIC_EVENT_TIMEOUT to 8000, for example, doInBackground would get called fine.
Ideas?

Android AsyncTask errors with onPostExecute

i have a question regarding the AsyncTask class in android, and why it is giving me an error. I have defined an inner class here..
class MyTask extends AsyncTask<String,String,Integer>{
Context context;
ProgressDialog dialog;
MyTask(Context c)
{
this.context = c;
}
//#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setMessage("Scanning Ports!");
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
for(intBeg = intBeg; intBeg <= intEnd; intBeg++
{
try
{
Socket s = new Socket(strMachine, intBeg);
isConnected += strMachine + " Is Listening On Port: " + intBeg + "\n";
Log.d("PORTSCAN", isConnected);
s.close();
}catch(Exception e){
notConnected += strMachine + " Is Not Listening On Port: " + intBeg + "\n";
//Toast.makeText(getBaseContext(), e.getMessage(), 3000).show();
Log.d("PORTSCAN", notConnected);
}
}
return 1;
}
protected void onPostExecute(Integer... params)
{
}
protected void onProgressUpdate(String... params)
{
}
}
However, when the doInBackground finishes, it supposed to call onPostExecute(), which never happens. And even when i try to use the "#Override" annotation over the onPostExecute(), it gives me an error saying onPostExecute must override a superclass method. I dont get what is happening! any help? Thanks!
onPostExcecute(Integer result) takes a single argument (no ...).
If the arguments don't match, it will not match the super method and will therefore not override it (and be called). Generally if #Override gives you an error something is wrong with your method name/parameters (or the superclass does not have such a method).
protected void onPostExecute(Integer params)//its single Integer object, not array of Integer objects
its java Varargs.and you can't change parameter of overrided method,You just change the Behaviour of override method.And its method of AsyncTask Class.
Just use this onPostExecuteMethod
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
Log.e("LOG", " on Post");
}
Check this code
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}

Categories

Resources