My Android application allows users to update their Facebook status from a Fragment. I’ve implemented the following AsyncTask so they can log in:
public class updateFacebookTask extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(final String... message) {
Log.i(TAG, "Async UFT");
myFResult = false;
Looper.prepare();
if (loginAndPostToWall()) {
Log.i(TAG, "loginAndPostToWall Returned: " + myFResult);
myFResult = true;
} else {
Log.i(TAG, "loginAndPostToWall Returned: " + myFResult);
myFResult = false;
}
//Looper.loop();
return myFResult;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(TAG, "UFT - oPrE");
}
@Override
protected void onPostExecute(Boolean myFResult) {
super.onPostExecute(myFResult);
if (myFResult) {
Log.i(TAG, "UFT oPE - Success: " + myFResult);
} else {
Log.w(TAG, "UFT oPE - fail: " + myFResult);
}
}
The AsyncTask uses the method loginAndPostToWall() as below, Which implements a DialogListener as part of the Facebook sdk:
public boolean loginAndPostToWall() {
myFResult = false;
facebook.authorize(getActivity(), PERMISSIONS,
Facebook.FORCE_DIALOG_AUTH, new DialogListener() {
public void onComplete(Bundle values) {
Log.i(TAG, "LoginDialog Complete - Success");
myFResult = true;
}
public void onFacebookError(FacebookError error) {
Log.w(TAG,
"onFacebookError - Authentication with Facebook failed");
myFResult = false;
}
public void onError(DialogError error) {
Log.w(TAG,
"onError - Authentication with Facebook failed");
looper = false;
Log.i(TAG, "looper " + looper);
myFResult = false;
}
public void onCancel() {
Log.w(TAG,
"onCancel - Authentication with Facebook cancelled");
myFResult = false;
}
});
return myFResult;
}
I have two problems that I really need help with please:
-
LogInAndPostToWall immediately returns myFResult as false. What I want it to do is wait until the login by webView has returned onComplete (or an error) from the DialogListener. How can I get it to return myFResult at that point and not before?
-
If I include Looper.loop(); onPostExecute is never called. If I don’t include Looper.prepare(); I get an error saying I can’t create a handler without it. Am I supposed to call quit() somewhere?
I’ve been stuck on this for two days (!) and have read many, many SO posts – I’ve tried using runnables and logging which threads everything is running on etc, but no joy.
Thanks in advance for saving me…
loginAndPostToWall() should be executed on the UI thread, as it modifyes the UI. doInBackgorund() method got never executed on UI thread and you should NOT ever include Looper.prepare() or Looper.loop() code there.