Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从子活动而不是主活动使用facebook登录_Android_Facebook_Android Fragments_Android Developer Api - Fatal编程技术网

Android 如何从子活动而不是主活动使用facebook登录

Android 如何从子活动而不是主活动使用facebook登录,android,facebook,android-fragments,android-developer-api,Android,Facebook,Android Fragments,Android Developer Api,我对所有这些facebook和android SDK的整合都是陌生的。 我按照facebook开发者提供的初学者教程进行了登录,结果成功了, 但当我将它与我的应用程序结合使用时,它无法工作,原因如下: 在我的项目中,我编写了一个从主活动到另一个Fragmentactivity(FBProfile)的调用,该活动调用登录片段。 facebook认证后,它将返回到MainActivity中的OnResume,而不是LoginFragment中的overided onActivityresult 我需

我对所有这些facebook和android SDK的整合都是陌生的。 我按照facebook开发者提供的初学者教程进行了登录,结果成功了, 但当我将它与我的应用程序结合使用时,它无法工作,原因如下:

在我的项目中,我编写了一个从主活动到另一个Fragmentactivity(FBProfile)的调用,该活动调用登录片段。 facebook认证后,它将返回到MainActivity中的OnResume,而不是LoginFragment中的overided onActivityresult

我需要创建此流(如果可能): MainActivity->FBProfile(FragmentActivity)->LoginFragment->Facebook->LoginFragment

由MainActivity调用的活动:

public class FBProfile extends FragmentActivity{


  private LoginFragment loginfragment; 


  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      // TODO Auto-generated method stub
      Log.i(" Facebook: ", "FBProfile->OnCreate");
      if(savedInstanceState==null)
      {
loginfragment=new LoginFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, loginfragment).commit();
}
else
{
loginfragment=(LoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}  
}
public class LoginFragment extends Fragment {
 private View login_view;
 private boolean isResumed = false;   
 private static final String TAG="LoginFragment";
 private UiLifecycleHelper uihelper;
 private LoginButton authbutton;
 private TextView userInfoTextView;
 private Session.StatusCallback callback=new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            // TODO Auto-generated method stub
            onSessionStatechange(session, state, exception);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.i(" Facebook: ", "FBProfile->OnCreate->LoginFragment");
        login_view=inflater.inflate(R.layout.profilepage, container,false);
       userInfoTextView = (TextView) login_view.findViewById(R.id.userInfoTextView);

        authbutton=(LoginButton) login_view.findViewById(R.id.login_button);
        authbutton.setFragment(this);
        authbutton.setReadPermissions(Arrays.asList("public_profile","email","user_birthday"));

        return login_view;
    }

    @SuppressWarnings("deprecation")
    private void onSessionStatechange(Session session,SessionState state,Exception exception)
    {
        if (isResumed) {
            if (session != null && session.isOpened()) {
                Intent intent = new Intent(getActivity(),
                        FBProfile.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
        if(state.isOpened()){
            Log.i(" Facebook: ", "LOGGED IN....");
            userInfoTextView.setVisibility(View.VISIBLE);

             // Request user data and show the results
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    // TODO Auto-generated method stub
                    if (user != null) {
                        // Display the parsed user info
                        userInfoTextView.setText(buildUserInfoDisplay(user));
                    }
                }
            });


            Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_LONG).show();
        }
        else
        {
             userInfoTextView.setVisibility(View.INVISIBLE);
            if (Session.getActiveSession() != null) {
                Session.getActiveSession().closeAndClearTokenInformation();
            }

            Session.setActiveSession(null);
            Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_LONG).show();
            Log.i(" Facebook: ", "LOGGED OUT....");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        uihelper=new UiLifecycleHelper(getActivity(), callback);
        uihelper.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Session session=Session.getActiveSession();
        if((session!=null)&&(session.isOpened()||session.isClosed()))
        {
            onSessionStatechange(session, session.getState(), null);

        }
        isResumed = true;
        uihelper.onResume();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        uihelper.onPause();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        uihelper.onSaveInstanceState(outState);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        uihelper.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("LoginFragment: ","onActivityResult Called");
        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    }
    /**
     * 
     * @param user
     * @return
     */
    private String buildUserInfoDisplay(GraphUser user) {
        StringBuilder userInfo = new StringBuilder("");

        // Example: typed access (name)
        // - no special permissions required
        userInfo.append(String.format("Name: %s\n\n", 
            user.getName()));

        // Example: typed access (birthday)
        // - requires user_birthday permission
        userInfo.append(String.format("Birthday: %s\n\n", 
            user.getBirthday()));

        // Example: partially typed access, to location field,
        // name key (location)
        // - requires user_location permission
  //      userInfo.append(String.format("Location: %s\n\n", 
  //          user.getLocation().getProperty("name")));

        // Example: access via property name (locale)
        // - no special permissions required
//        userInfo.append(String.format("Locale: %s\n\n", 
 //           user.getProperty("locale")));

        // Example: access via key for array (languages) 
        // - requires user_likes permission
        JSONArray languages = (JSONArray)user.getProperty("languages");
        if (languages.length() > 0) {
            ArrayList<String> languageNames = new ArrayList<String> ();
            for (int i=0; i < languages.length(); i++) {
                JSONObject language = languages.optJSONObject(i);
                // Add the language name to a list. Use JSON
                // methods to get access to the name field. 
                languageNames.add(language.optString("name"));
            }           
            userInfo.append(String.format("Languages: %s\n\n", 
            languageNames.toString()));
        }

        return userInfo.toString();
    }
}
从FBProfile调用的登录片段:

public class FBProfile extends FragmentActivity{


  private LoginFragment loginfragment; 


  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      // TODO Auto-generated method stub
      Log.i(" Facebook: ", "FBProfile->OnCreate");
      if(savedInstanceState==null)
      {
loginfragment=new LoginFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, loginfragment).commit();
}
else
{
loginfragment=(LoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}  
}
public class LoginFragment extends Fragment {
 private View login_view;
 private boolean isResumed = false;   
 private static final String TAG="LoginFragment";
 private UiLifecycleHelper uihelper;
 private LoginButton authbutton;
 private TextView userInfoTextView;
 private Session.StatusCallback callback=new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            // TODO Auto-generated method stub
            onSessionStatechange(session, state, exception);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.i(" Facebook: ", "FBProfile->OnCreate->LoginFragment");
        login_view=inflater.inflate(R.layout.profilepage, container,false);
       userInfoTextView = (TextView) login_view.findViewById(R.id.userInfoTextView);

        authbutton=(LoginButton) login_view.findViewById(R.id.login_button);
        authbutton.setFragment(this);
        authbutton.setReadPermissions(Arrays.asList("public_profile","email","user_birthday"));

        return login_view;
    }

    @SuppressWarnings("deprecation")
    private void onSessionStatechange(Session session,SessionState state,Exception exception)
    {
        if (isResumed) {
            if (session != null && session.isOpened()) {
                Intent intent = new Intent(getActivity(),
                        FBProfile.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
        if(state.isOpened()){
            Log.i(" Facebook: ", "LOGGED IN....");
            userInfoTextView.setVisibility(View.VISIBLE);

             // Request user data and show the results
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    // TODO Auto-generated method stub
                    if (user != null) {
                        // Display the parsed user info
                        userInfoTextView.setText(buildUserInfoDisplay(user));
                    }
                }
            });


            Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_LONG).show();
        }
        else
        {
             userInfoTextView.setVisibility(View.INVISIBLE);
            if (Session.getActiveSession() != null) {
                Session.getActiveSession().closeAndClearTokenInformation();
            }

            Session.setActiveSession(null);
            Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_LONG).show();
            Log.i(" Facebook: ", "LOGGED OUT....");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        uihelper=new UiLifecycleHelper(getActivity(), callback);
        uihelper.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Session session=Session.getActiveSession();
        if((session!=null)&&(session.isOpened()||session.isClosed()))
        {
            onSessionStatechange(session, session.getState(), null);

        }
        isResumed = true;
        uihelper.onResume();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        uihelper.onPause();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        uihelper.onSaveInstanceState(outState);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        uihelper.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("LoginFragment: ","onActivityResult Called");
        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    }
    /**
     * 
     * @param user
     * @return
     */
    private String buildUserInfoDisplay(GraphUser user) {
        StringBuilder userInfo = new StringBuilder("");

        // Example: typed access (name)
        // - no special permissions required
        userInfo.append(String.format("Name: %s\n\n", 
            user.getName()));

        // Example: typed access (birthday)
        // - requires user_birthday permission
        userInfo.append(String.format("Birthday: %s\n\n", 
            user.getBirthday()));

        // Example: partially typed access, to location field,
        // name key (location)
        // - requires user_location permission
  //      userInfo.append(String.format("Location: %s\n\n", 
  //          user.getLocation().getProperty("name")));

        // Example: access via property name (locale)
        // - no special permissions required
//        userInfo.append(String.format("Locale: %s\n\n", 
 //           user.getProperty("locale")));

        // Example: access via key for array (languages) 
        // - requires user_likes permission
        JSONArray languages = (JSONArray)user.getProperty("languages");
        if (languages.length() > 0) {
            ArrayList<String> languageNames = new ArrayList<String> ();
            for (int i=0; i < languages.length(); i++) {
                JSONObject language = languages.optJSONObject(i);
                // Add the language name to a list. Use JSON
                // methods to get access to the name field. 
                languageNames.add(language.optString("name"));
            }           
            userInfo.append(String.format("Languages: %s\n\n", 
            languageNames.toString()));
        }

        return userInfo.toString();
    }
}
公共类LoginFragment扩展了片段{
私有视图登录\ u视图;
私有布尔值isResumed=false;
私有静态最终字符串TAG=“LoginFragment”;
私人UiLifecycleHelper uihelper;
私人登录按钮;
私有文本视图用户信息文本视图;
private Session.StatusCallback callback=新建会话.StatusCallback(){
@凌驾
公共无效调用(会话、会话状态、异常){
//TODO自动生成的方法存根
onSessionStatechange(会话、状态、异常);
}
};
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//TODO自动生成的方法存根
Log.i(“Facebook:,“FBProfile->OnCreate->LoginFragment”);
登录\查看=充气机。充气(R.layout.profilepage,container,false);
userInfoTextView=(TextView)login\u view.findviewbyd(R.id.userInfoTextView);
authbutton=(LoginButton)login_view.findViewById(R.id.login_按钮);
setFragment(this);
authbutton.setReadPermissions(Arrays.asList(“public_profile”、“email”、“user_birth”));
返回登录视图;
}
@抑制警告(“弃用”)
private void OnSessionState更改(会话、会话状态、异常)
{
如果(已使用){
if(session!=null&&session.isOpened()){
意向意向=新意向(getActivity(),
FBProfile.class);
intent.addFlags(intent.FLAG\u活动\u清除\u顶部
|意图。标记活动(新任务);
星触觉(意向);
}
}
if(state.isOpened()){
Log.i(“Facebook:,“登录…”);
userInfoTextView.setVisibility(View.VISIBLE);
//请求用户数据并显示结果
Request.executeRequestAsync(会话,新请求.GraphUserCallback(){
@凌驾
未完成公共无效(GraphUser用户,响应){
//TODO自动生成的方法存根
如果(用户!=null){
//显示已解析的用户信息
setText(buildUserInfoDisplay(用户));
}
}
});
Toast.makeText(getActivity(),“登录”,Toast.LENGTH_LONG.show();
}
其他的
{
userInfoTextView.setVisibility(View.INVISIBLE);
if(Session.getActiveSession()!=null){
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
Toast.makeText(getActivity(),“Logged Out”,Toast.LENGTH_LONG.show();
Log.i(“Facebook:,“注销…”);
}
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
uihelper=newUILifecycleHelper(getActivity(),回调);
uihelper.onCreate(savedInstanceState);
}
@凌驾
恢复时公开作废(){
//TODO自动生成的方法存根
super.onResume();
Session=Session.getActiveSession();
if((session!=null)&&(session.isOpened()| | session.isClosed())
{
onSessionStatechange(会话,session.getState(),null);
}
isResumed=真;
uihelper.onResume();
}
@凌驾
公共无效暂停(){
//TODO自动生成的方法存根
super.onPause();
uihelper.onPause();
}
@凌驾
SaveInstanceState上的公共无效(束超出状态){
//TODO自动生成的方法存根
super.onSaveInstanceState(超出状态);
uihelper.onSaveInstanceState(outState);
}
@凌驾
公共空间{
//TODO自动生成的方法存根
super.ondestory();
uihelper.ondestory();
}
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
Log.i(“LoginFragment:,“onActivityResult调用”);
Session.getActiveSession().onActivityResult(getActivity(),requestCode,resultCode,data);
}
/**
* 
*@param用户
*@返回
*/
私有字符串buildUserInfoDisplay(GraphUser用户){
StringBuilder userInfo=新的StringBuilder(“”);
//示例:类型化访问(名称)
//-无需特殊权限
userInfo.append(String.format(“名称:%s\n\n”),
user.getName());
//示例:键入访问(生日)
//-需要用户权限
userInfo.append(String.format(“生日:%s\n\n”,
user.getBirthday());
//示例:部分键入的“访问位置”字段,
//名称键(位置)
//-需要用户位置权限
//userInfo.append(String.format(“位置:%s\n\n”),
/