嗨,我必须从托管片段的活动发布我的状态,并首次使用应用程序,登录应用程序后,当我尝试更新状态时出现异常。我得到了这个例外。
“会话:尝试为具有待处理请求的会话请求新权限。”
这是我的片段代码
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.carfrenzy.activities.FeedsActivity;
import com.carfrenzy.activities.SelectCarActivity;
import com.carfrenzy.activities.TourActivity;
import com.carfrenzy.activities.UserProfileActivity;
import com.carfrenzy.app.R;
import com.carfrenzy.beans.CFConstants;
import com.carfrenzy.beans.UserProfileInfo;
import com.carfrenzy.ui.ProgressBarDialog;
import com.carfrenzy.webservices.WebHttpServicesManager;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.turbomanage.httpclient.AsyncCallback;
import com.turbomanage.httpclient.HttpResponse;
public class MainFragment extends Fragment
{
private UiLifecycleHelper uiHelper;
String accessToken = "";
SharedPreferences mprefs;
String mTutorial = "";
static Context context;
static Context mcontext;
Button login;
EditText etemail, etpass;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final List<String> EMAIL_PERMISSIONS = Arrays.asList("email");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private static boolean pendingPublishReauthorization = false;
final String pushNotificationToken = "";
String android_id = "";
String pushToken = "";
private static final String TAG = "MainFragment";
ImageView iemail;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, Arrays.asList("email"));
LoginButton authButton = null;
//private ProgressDialog mProgressDialog = null;
Handler handler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
context = getActivity().getBaseContext();
mcontext = getActivity();
View view = inflater.inflate(R.layout.startup, container, false);
etemail = (EditText) view.findViewById(R.id.etUser);
etpass = (EditText) view.findViewById(R.id.etPass);
login = (Button) view.findViewById(R.id.bLoginNew);
login.setEnabled(true);
authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setBackgroundResource(R.drawable.logo_facebook);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email"));
View viewp = inflater.inflate(R.layout.user_mycar_home, container, false);
/***************/
android_id = Secure.getString(getActivity().getContentResolver(), Secure.ANDROID_ID);
login.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (etemail.getText().toString().equals("") || etpass.getText().toString().equals(""))
{
Toast.makeText(context, "Please enter your email address and password to login", Toast.LENGTH_SHORT).show();
}
else if (etpass.getText().toString().length() < 6)
{
Toast.makeText(context, "Password is invalid. It should be atleast 6 characters", Toast.LENGTH_SHORT).show();
}
else if (etpass.getText().toString().length() > 5)
{
//pushToken=getRegistrationId(context);
//Log.i("Audit", pushToken);
//mProgressDialog = ProgressDialog.show(getActivity(),
// "Cruising...","", true);
//mProgressDialog.setCancelable(true);
final ProgressBarDialog dialogBar = new ProgressBarDialog(getActivity(), "Cruising...");
//
dialogBar.show();
pushToken= mprefs.getString("PROPERTY_REG_ID", "");
Log.i("Audit", pushToken);
new WebHttpServicesManager(context).signInWithEmail(etemail.getText().toString(), etpass.getText().toString(), android_id.toString(), pushToken.toString(), new AsyncCallback()
{
@Override
public void onComplete(HttpResponse httpResponse)
{
dialogBar.dismiss();
if (httpResponse != null && httpResponse.getStatus() == 200)
{
//mProgressDialog.dismiss();
String responseString = WebHttpServicesManager.decompress(httpResponse.getBody());
JSONObject jsonResponse=null;
JSONObject status;
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse(responseString);
try
{
if( o!=null && o.get("status").getAsString().equals("1"))
{
jsonResponse = new JSONObject(responseString);
JSONObject response = jsonResponse.getJSONObject("response");
String active1 = response.getString("activeSalt");
mprefs.edit().putString("activeSalt", active1).commit();
Boolean tour = mprefs.getBoolean(TourActivity.SharedPrefKey, false);
if (tour)
{
// Intent intent = new
// Intent(context,TourActivity.class);
// startActivity(intent);
// tourDon();
}
}
else
{
jsonResponse = new JSONObject(responseString);
JSONObject response = jsonResponse.getJSONObject("response");
Toast.makeText(context, "Error:"+ response.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String isTutorial = mprefs.getString("isTutorial", "");
// if(isTutorial.equalsIgnoreCase("1"))
// {
// Intent in = new Intent(context, SelectCarActivity.class);
// in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// login.setEnabled(false);
// startActivity(in);
// getActivity().finish();
// }
// else
// {
Intent in = new Intent(context, UserProfileActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.setEnabled(false);
startActivity(in);
// Log.i("SignIn", "Success");
getActivity().finish();
return;
//}
}
else if (httpResponse !=null && httpResponse.getStatus()==401)
{
// AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Oops").setMessage("Cannot connect to server please Try again with valid email and password!").setNeutralButton("OK", null);
// AlertDialog alert1 = alert.create();
// alert1.show();
String responseString = WebHttpServicesManager.decompress(httpResponse.getBody());
//JSONObject jsonResponse=null;
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse(responseString);
String message = o.get("response").getAsString();
AlertDialog.Builder alert = new AlertDialog.Builder(mcontext).setTitle("Error").setMessage(" " +message ).setNeutralButton("OK", null);
alert.show();
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(mcontext).setTitle("Oops").setMessage("Cannot connect to server. Please Try again!" ).setNeutralButton("OK", null);
alert.show();
}
}
@Override
public void onError(Exception e, int errorCode)
{
super.onError(e, errorCode);
//mProgressDialog.dismiss();
dialogBar.dismiss();
if (errorCode == CFConstants.INTERNET_NOT_AVAILABLE)
{
// AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("No Internet Connectivity").setMessage("Please Check Your Internet Connection and Try again!").setNeutralButton("OK", null);
// AlertDialog alert1 = alert.create();
// alert1.show();
Toast toast = Toast.makeText(mcontext, "Please Check Your Internet Connection and Try again!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
Log.i("SignIn", "Error");
}
@Override
public void onComplete(org.apache.http.HttpResponse httpResponse)
{
// TODO Auto-generated method stub
//mProgressDialog.dismiss();
dialogBar.dismiss();
}
});
}
}
});
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception)
{
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
if (state.isOpened())
{
if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED))
{
pendingPublishReauthorization = false;
publishStory();
}
else if (!pendingPublishReauthorization)
{
try
{
Log.i("Audit", "Logged in...");
Log.i("fb2", accessToken);
// Check for email permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(EMAIL_PERMISSIONS, permissions))
{
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
accessToken = session.getAccessToken();
UserProfileInfo.setAccessToken(accessToken);
pushToken= mprefs.getString("PROPERTY_REG_ID", "");
facebookLogin(accessToken, pushToken);
}
catch(Exception e )
{
e.printStackTrace();
}
}
}
else if (state.isClosed())
{
Toast.makeText(context, "Error: Can't Login through Facebook! Please try again later!", Toast.LENGTH_SHORT).show();
}
}
private Session.StatusCallback callback = new Session.StatusCallback()
{
@Override
public void call(Session session, SessionState state, Exception exception)
{
onSessionStateChange(session, state, exception);
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
mprefs = getActivity().getSharedPreferences("com.carfrenzy.app", getActivity().MODE_PRIVATE);
android_id = Secure.getString(getActivity().getContentResolver(), Secure.ANDROID_ID);
pushToken= mprefs.getString("PROPERTY_REG_ID", "");
Boolean firstTour = mprefs.getBoolean(TourActivity.firstTimTour, false);
}
@Override
public void onResume()
{
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed()))
{
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.v("in activity result of :::", "Main fragment");
uiHelper.onActivityResult(requestCode, resultCode, data);
//Session.getActiveSession().onActivityResult((Activity) context, requestCode, resultCode, data);
Log.i("Audit", "I am here in Result of fragment");
}
@Override
public void onPause()
{
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy()
{
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void facebookLogin(final String accessToken, final String pushToken)
{
String mAccessToken = UserProfileInfo.getAccessToken();
Log.i("Audit", mAccessToken);
// final ProgressBarDialog dialogBar = new ProgressBarDialog(context, "Cruising...");
// dialogBar.show();
Toast toast = Toast.makeText(mcontext, "Fetching data from Facebook Servers! This may take few seconds!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
//Toast.makeText(context, "Fetching data from Facebook Servers! This may take few seconds!", Toast.LENGTH_SHORT).show();
new WebHttpServicesManager(getActivity()).signInFacebook("1", accessToken.toString(), android_id.toString(), pushToken.toString(), new AsyncCallback()
{
public void onComplete(HttpResponse httpResponse)
{
// dialogBar.dismiss();
if (httpResponse != null && httpResponse.getStatus() == 200)
{
String responseString = WebHttpServicesManager.decompress(httpResponse.getBody());
Log.e("SignUp", " Server data : " + httpResponse.getBodyAsString());
JSONObject jsonResponse = null;
JSONObject status;
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject) parser.parse(responseString);
try
{
if (o != null && o.get("status").getAsString().equals("1"))
{
jsonResponse = new JSONObject(responseString);
JSONObject response = jsonResponse.getJSONObject("response");
String active1 = response.getString("activeSalt");
mprefs.edit().putString("activeSalt", active1).commit();
mTutorial = response.getString("userTutorial");
mprefs.edit().putString("userTutorial", mTutorial);
String suggestedTour = response.getString("isSuggestedTour");
mprefs.edit().putString("suggestedTour", suggestedTour);
}
else
{
jsonResponse = new JSONObject(responseString);
JSONObject response = jsonResponse.getJSONObject("response");
Toast.makeText(context, "Error:" + response.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
if (mTutorial.toString().equals("1"))
{
Intent intent = new Intent(getActivity(), SelectCarActivity.class);
intent.putExtra("fbAccessToken", accessToken);
getActivity().startActivity(intent);
Log.i("SignInFacebook", "Success");
}
else if (mTutorial.toString().equals("0"))
{
Intent intent = new Intent(getActivity(), FeedsActivity.class);
intent.putExtra("fbAccessToken", accessToken);
getActivity().startActivity(intent);
}
}
else if (httpResponse != null && httpResponse.getStatus() == 401)
{
//new AlertDialog.Builder(context).setTitle("Cannot connect to server").setMessage("We cannot connect to server! Please try again Later!").setNeutralButton("OK", null).show();
// dialogBar.dismiss();
Toast.makeText(context, "We cannot connect to server! Please try again Later!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Exception e, int errorCode)
{
super.onError(e, errorCode);
// dialogBar.dismiss();
if (errorCode == CFConstants.INTERNET_NOT_AVAILABLE)
{
//new AlertDialog.Builder(context).setTitle("No Internet Connectivity").setMessage("Please Check Your Internet Connection and Try again!").setNeutralButton("OK", null).show();
// dialogBar.dismiss();
Toast.makeText(context, "Please Check Your Internet Connection and Try again!", Toast.LENGTH_LONG).show();
}
Log.i("SignUp", "error");
}
@Override
public void onComplete(org.apache.http.HttpResponse httpResponse)
{
// dialogBar.dismiss();
}
});
}
public static void publishStory()
{
Session session = Session.getActiveSession();
if (session != null)
{
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions))
{
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest((Activity) mcontext, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
final ProgressBarDialog dialogBar = new ProgressBarDialog(mcontext, "Cruising...");
//
dialogBar.show();
Bundle postParams = new Bundle();
postParams.putString("name", "Motoqlik");
postParams.putString("caption", "You can now Look out for road users via motoqlik");
postParams.putString("description", "A smart new way to look out for road users! Look out for one another on roads and car park!");
postParams.putString("link", "http://www.motoqlik.com/");
postParams.putString("picture", "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc3/c57.33.414.414/s160x160/972186_590988330944636_1055194609_n.png");
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
dialogBar.dismiss();
if (response != null)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
Log.i(TAG, "postId " + postId);
Toast.makeText(context, "Shared on your profile"+ postId, Toast.LENGTH_LONG).show();
// AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Success").setMessage("Shared on your wall" + postId).setNeutralButton("OK", null);
//alert.show();
}
catch (JSONException e)
{
Log.i(TAG, "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null)
{
Toast.makeText((Activity) context, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
//AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Sharing Error").setMessage("Cannot connect to facebook Servers!" + error.getErrorMessage()).setNeutralButton("OK", null);
//alert.show();
}
else
{
}
}
else
{
Toast.makeText(context, "Could not Connect to Facebook!", Toast.LENGTH_LONG).show();
// AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Sharing Error").setMessage("Cannot connect to facebook Servers!").setNeutralButton("OK", null);
//alert.show();
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private static boolean isSubsetOf(Collection<String> subset, Collection<String> superset)
{
for (String string : subset)
{
if (!superset.contains(string))
{
return false;
}
}
return true;
}
}
publishStory() 方法是在我的墙上发帖的实际方法。正在从主机活动调用此方法。并且 UILifeCycleHelper 处理是在片段的 onActivityResult 中完成的,但是在发布故事之后片段的 onActivityResult 没有被调用。这只发生在用户第一次使用应用程序并尝试发布到 facebook 时。如果他注销并再次登录,那么他可以成功发布并且不会引发异常。任何形式的帮助将不胜感激,
谢谢和问候, 穆纳扎